I have Action Method which calls service function using `System.Threading.Task`.

The service function has a static global variable which I have set attribute `ThreadStatic` to make my function Thread-Safe.

My issue is that sometimes when I run my action method the shared variable `_sharedList` throws null reference exception when accessing it in my `HotelService`.

Here is a sample implementation to replicate the issue:

**Controller Action Method calling HotelService.TestMultiThread**

```
public ActionResult MultiThread()
{
  HotelService svc = new HotelService();
  var resp = new List<TestPnrHeaderResponse>();

  var tasks = Enumerable.Range(0, 5).Select(i => Task.Run(() => svc.TestMultiThread(i)));

  var results = await Task.WhenAll(tasks);

  return View(resp);
}

```

**HotelService class**

> 
> **\_sharedList is Null in line `_sharedList.listInt.AddRange(GetIntList());`**
> 
> 
> 

```
public class HotelService
{
    [ThreadStatic]
    private static TestPnrHeaderResponse _sharedList;

    private void LoadCache()
    {
        _sharedList = new TestPnrHeaderResponse();
        _sharedList.PnrLegs = new List<PnrLegVM>();
        _sharedList.listInt = new List<int>();
        Task.Factory.StartNew(() =>
        {
            _sharedList.listInt.AddRange(GetIntList());
        });
    }

    private IEnumerable<int> GetIntList()
    {
        return Enumerable.Range(0, 5);
    }
    public TestPnrHeaderResponse TestMultiThread(int count)
    {
        LoadCache();

        if (count % 2 == 0)
        {
            _sharedList.PnrLegs.Add(new PnrLegVM
            {
                ApplicationType = count.ToString(),
                PKCity = count,
                PKNationality = 1,
                PKPnrHeader = 1,
                PKPnrLeg = 1
            });
        }
        else
        {
            _sharedList.PnrLegs.Add(new PnrLegVM
            {
                ApplicationType = count.ToString(),
                PKCity = count,
                PKNationality = 99,
                PKPnrHeader = 99,
                PKPnrLeg = 99
            });

        }
        return _sharedList;
    }
}

```

**Shared Variable class**

```
public class TestPnrHeaderResponse
{
   public List<PnrLegVM> PnrLegs { get; set; }
   public List<int> listInt { get; set; }
}
public class PnrLegVM
{
   public int PKPnrLeg{get;set;}

   public int PKPnrHeader{get;set;}      
   public string ApplicationType{get;set;}
   public int PKNationality {get;set;}
}

```

Please help to find solution for this. Also, is there a better way to make the function Thread-safe as it uses many shared variables in actual implementation.