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.