Sunil
Sunil

Reputation: 21416

Is Session variable thread-safe within a Parallel.For loop in ASP.Net page

Would changing a session variable (i.e. Session["Progress"]) in code below be safe?

This code is part of code-behind of an ASP.Net page.

When running a loop in parallel, two iterations could run simultaneously and cause issues if the same session variable is changed by both iterations.

   public void LongOperation()
    {
        Parallel.For(0, totalMembers,(i,loopState) =>
        {
            Thread.Sleep(2000);//wait some time to simulate processing
            progress++;
            Session["Progress"] = progress;//IS THIS THREAD-SAFE?
        } 
       ); 
   }

Upvotes: 1

Views: 1720

Answers (1)

Aristos
Aristos

Reputation: 66649

This is NOT thread safe, but the session across different open page is safe to change.

So under certain circumstances if you call it is safe.

If you call it only one time from you page, then is safe across different pages. The reason for that is that the session is fully lock the session from the start of page load up to the end.

Some similar answers to prove that.

Web app blocked while processing another web app on sharing same session
Does ASP.NET Web Forms prevent a double click submission?
Trying to make Web Method Asynchronous

If you call it more than one time from the same page, from different threads, then you need synchronization.

Notes

  • If this loop is take long to complete then all users will be wait for that calculations and not only the session user. All users will be lock down by the session lock. If too many users call that then all users together will be wait for long time. So you may need to make this calculations on a scheduler task.
  • If the time to process the data inside the loop is smaller than the time the loop takes to create and synchronize the threads, then the parallel loop is takes more time to complete than the a simple loop. So you need to calculate the speed here for the simple loop and the parallel loop.

Upvotes: 3

Related Questions