What is the problem of the following code?
Task.Factory.StartNew(() =>
{
while (true)
{
Console.WriteLine("@ " + DateTime.Now.ToString());
Thread.Sleep(TimeSpan.FromSeconds(2));
}
});
var task = Task.Factory.StartNew(() =>
{
while (true)
{
Console.WriteLine("! " + DateTime.Now.ToString());
Thread.Sleep(TimeSpan.FromSeconds(4));
}
});
Task.WaitAll(task);
The main problem is related to Thread.Sleep. Using this method in combination with tasks we can gen odd behavior and in the end the performance of the tasks can be affected. One of the behavior that we could get is related to how the sleep period – that will not be the same as we expect ("random" sleep interval).
This occurs because of the TPL behavior, which will not guarantee that each task will have a dedicated thread where he can run.
What we should do to resolve this problem?
We have two possible solution.
1. One solution is to create a timer for each task. This would work 100% and for this example the solution is the way how we should implemented this from the start.
2. In other cases we wouldn't be able to use timers and we would like to be able to put the task in sleep. In the case we have a long running task, than we could set the TaskCreationOption to LongRunning. This will notify TPL that this task is a long running task and will create a dedicate thread for it.
Task.Factory.StartNew(() =>
{
while (true)
{
Console.WriteLine("@ " + DateTime.Now.ToString());
Thread.Sleep(TimeSpan.FromSeconds(2));
}
},TaskCreationOptions.LongRunning);
var task = Task.Factory.StartNew(() =>
{
while (true)
{
Console.WriteLine("! " + DateTime.Now.ToString());
Thread.Sleep(TimeSpan.FromSeconds(4));
}
}, TaskCreationOptions.LongRunning);
Task.WaitAll(task);
Comments
Post a Comment