问题
So I am attempting to process records from a datatable one row at a time. I am new to multi-threaded environments and I was asked to use Parallel.Foreach Loop. I wanted to know how local variables are treated in a Parallel execution mode. Following is my code.
Parallel.ForEach(dtReportData.Tables[0].AsEnumerable(), drow =>
{
string strType = drow["type"];
//Based on this type, I am executing logic from a switch case.
});
Now. I want to know if I can declare and assign value to the variable inside the loop. For an instance, let's assume that there are 2 threads running in parallel.
Thread 1 fetched a record and let's say that the value that was fetched was "Type1" and stored into strType. Now, I want my code to perform the logic for type "Type1" (Let's assume that we have written a switch case for it)
However, let's assume that before Thread 1 starts executing the logic, thread 2 comes into play. Thread 2 assigns the value "Type2" to the strType.
Now, when Thread 1 goes to my Switch block, what value will it hold? Will it be "Type1" or "Type2".
Note that I am not globally declaring the value of the String variable outside the Foreach loop, it's inside the loop and I believe that a new instance is created everytime.
回答1:
The variable strType
is local to this lambda invocation, and no other thread is able to see it or modify it. Its value is stored in the stack of the current thread. Each thread has its own stack, with a size of 1 MB.
As a side note, be aware that the ADO.NET classes in general, and the DataTable
class in particular, are not thread-safe. If you try to mutate them from multiple threads in parallel, their internal state may become corrupted, and their behavior will become undefined.
来源:https://stackoverflow.com/questions/61192617/can-i-use-local-variables-inside-a-parallel-foreach-loop-without-unintentionall