I wrote this console program:
static void Main(string[] args)
{
object sync = new object();
Thread[] t = new Thread[10];
int count = 0;
for (var i = 0; i < t.Length; i++)
{
t[i] = new Thread(() =>
{
lock (sync)
{
int inc = count;
Console.WriteLine("Count: {0}", count);
count = inc + 1;
}
});
}
foreach (var t1 in t)
{
t1.Start();
}
foreach (var t1 in t)
{
t1.Join();
Console.WriteLine("\nFinal Count= {0}", count);
Console.ReadKey();
}
}
I get this result in the output :
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Final Count= 7
Count: 8
Count: 9
and when I run the app multiple time I'm getting more different results but I want to see this result :
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Count: 8
Count: 9
Final Count= 10
why does it return different results and how do I fix this?
Try do don't manually create/terminate threads like this, it's a time consuming operation and it doesn't scale well.
Use the ThreadPool
instead.
Or better: use tasks , and synchronize them by using await Task.WhenAll(list of your tasks)
Well, instead of this :
foreach (var t1 in t)
{
t1.Join();
Console.WriteLine("\nFinal Count= {0}", count);
Console.ReadKey();
}
You should write:
foreach (var t1 in t)
{
t1.Join();
}
Console.WriteLine("\nFinal Count= {0}", count);
Console.ReadKey();
Otherwise you will have a racing and your code will be undeterministic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.