1

I have below code at my ASP.NET 4.0 web application's Global.asax

protected void Application_Start(object sender, EventArgs e)
{
  Dictionary<string, string> AllCompanyList = new Dictionary<string, string>();
  Application.Add("GlobalCompanyList", AllCompanyList);

  Thread ProcessCompanyThread = new Thread(new ParameterizedThreadStart(CompanyThread.Start));
  ProcessCompanyThread.IsBackground = true;
  ProcessCompanyThread.Start(AllCompanyList);
}

I access it on another page by

Dictionary<string, string> AllCompanyList = (Dictionary<string, string>)HttpContext.Current.Application["GlobalCompanyList"];
  1. First of all, is "GlobalCompanyList" only has one instance in IIS's lifetime?

  2. Second, is "GlobalCompanyList" thread safe to be access or modify in ProcessCompanyThread? If it is not then what must i do to make it thread safe?

Thanks for help.

1 Answers1

1

1) AllCompanyList will only have one instance for the lifetime of the Application Instance. IIS can and will start and stop application instances at will (and even have more than application instance running at one time) depending on how it is configured.

GlobalCompanyList is not inherently thread safe. You can make reading and writing to it safe by locking it.

lock(AllCompanyList)
{
    //make changes
}

Thread safety and concurrency is complicated - even the above is not totally safe because it doesn't prevent someone from attempting:

Application["GlobalCompanyList"].Add()...

which is outside of a lock. The best approach if thread safety is needed would be to encapsulate your company list in a thread safe object.

Joe Enzminger
  • 11,110
  • 3
  • 50
  • 75