I am trying to understand the benefits of Task Parallel library over using traditional multi threading and when I think about the below situation, I am stuck thinking does it handle race condition or do we need to handle this in our code?
Here is my code:
int depdt = 0;
Parallel.For(1, 10, mem =>
{
for (int dep = 1; dep <= 10; dep++)
{
depdt = dep;
Console.WriteLine("MEMBER: " + mem + " " + "Dependent: " + dep);
}
Console.WriteLine("Dep Value: " + depdt + " " + "mem: " + mem);
});
Console.ReadKey();
I ran it couple of times and I don't see any thread interfering/overwriting the the "depdt" variable. But I need to confirm this. (or) To make it thread safe should I manually create an instance of class and implement it like the below code to avoid race conditions
int depdt = 0;
Parallel.For(1, 10, mem =>
{
Worker worker = new Worker();
worker.DoWork(mem);
});
Console.ReadKey();
public class Worker
{
public void DoWork(int mem)
{
int depdt = 0;
for (int dep = 1; dep <= 10; dep++)
{
depdt = dep;
Console.WriteLine("MEMBER: " + mem + " " + "Dependent: " + dep);
}
Console.WriteLine("Dep Value: " + depdt +" "+ "mem: "+ mem);
}
}
Response to @yms: I mean when using normal threads the varaible depdt becomes unreliable. Here is my code:
for (int mem = 1; mem <= 10; mem++)
{
var t= new Thread(state =>
{
for (int dep = 1; dep <= 10; dep++)
{
depdt = dep;
Console.WriteLine("MEMBER: " + mem + " " + "Dependent: " + dep);
}
Console.WriteLine("Dep Value: " + depdt + " " + "mem: " + mem);
});
t.Start(string.Format("Thread{0}", mem));
}
Console.ReadKey();
Here is my output screen: Infact both mem and dep variables have become unreliable