multithreading - Is Session variable thread-safe within a Parallel.For loop in ASP.Net page -
Would it be safe to change a session variable (i.e., the session ["progress"]) in the code below?
This code is part of the code-behind of the ASP.Net page.
On running a loop in parallel, two iterations run simultaneously and the same session variable has been replaced by both iterations.
public zero-long operation () {parallel. (0, Total Member, (i, LoopState) => {Thread. Sleep (2000); Wait for some time ++; session ["Progress"] = Progress to simulate processing progress; // Is this thread-safe?}); }
This thread is not secure , but Is safe to change sessions in separate open pages .
So if you call in certain circumstances, then it is safe.
This is because the only one time from your page , then it is safe in different pages, because the session is fully loaded from the beginning of the page load to the session Locks up
To prove some similar answers.
If you call it different threads from from the same page , You need synchronization
notes
- If this loop takes a long time to complete then all users will calculate that calculation And will not only lock the session user all users will be locked by session lock if many users make calls then all users will be together Sector will wait longer. So you may need to calculate this on a scheduler task.
- If the time to process the data inside the loop the time of the loop decreases and synchronize threads from that time, then the parallel loop It takes more time to complete with a simple loop. So you need to calculate the speed for a simple loop and parallel loop.
Comments
Post a Comment