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?
        } 
       ); 
   }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x