I used "lock" in the "task" it doesn't work and race condition occurred
I have defined a Counter, which should eventually return 0, because a Method increases the value of the Counter and a Method decreases it.
And when I use Thread it is not a problem. This problem occurs when I use Task
I use lock and monitor But it did not work again and gave the same result as before
namespace ConsoleApp1
{
public class LockDemo
{
private readonly static object _lock = new object();
private static int _count = 0;
public void Main()
{
var tasks = new List<Task>();
for (int i = 0; i < 1000; i++)
{
tasks.Add(new Task(() => IncrementCounter()));
tasks.Add(new Task(() => DecrementCounter()));
}
foreach (var item in tasks)
{
item.Start();
}
}
void IncrementCounter()
{
Console.WriteLine("wait for opening lock...");
lock (_lock)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("enter the critical section");
_count += 1;
Console.WriteLine("Counter:" + _count);
Console.ForegroundColor = ConsoleColor.White;
}
Console.WriteLine("exit critical section");
}
void DecrementCounter()
{
Console.WriteLine("wait for opening lock...");
lock (_lock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("enter the critical section");
_count -= 1;
Console.WriteLine("Counter:" + _count);
Console.ForegroundColor = ConsoleColor.White;
}
Console.WriteLine("exit critical section");
}
}
}
You're creating two thousand tasks: 1,000 increment and 1,000 decrement. Even though you're starting the tasks in a specific order, there's no guarantee they will execute in that order because they're running asynchronously. Its possible for two decrements to happen, and then a single increment, etc. - which is likely what you're seeing here.
Also, it is not recommended to use Task.Start
Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
https://devblogs.microsoft.com/pfxteam/task-factory-startnew-vs-new-task-start/