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

前端 未结 1 2034
南方客
南方客 2021-01-26 18:38

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 i

相关标签:
1条回答
  • 2021-01-26 19:01

    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.
    0 讨论(0)
提交回复
热议问题