Factory.StartNew leads to code execution blockage when I don't used Thread.Sleep(20);
I tried the following:
Thread.Sleep()
- This works with Factory.StartNew & produces desirable resultTask.Delay(20)
- This doesn't work with Factory.StartNewTask<bool>.Run
- Using this instead of Factory.StartNew doesn't make any difference
The code:
private async Task<bool> GetStatus()
{
var MyTask = Task<bool>.Factory.StartNew( () =>
//var MyTask = Task<bool>.Run( () => // Using Task.Run doesn't make any
//difference
{
while (true)
{
if (EventStatus.ToString() == "Rejected")
break;
if (EventStatus.ToString() == "Error")
break;
Thread.Sleep(20);// This gives the desirable result.Removing it
//causes application to hang
//Task.Delay(20);// This line doesn't make any difference
}
return true;
});
MyTask.Wait();
return await MyTask;
}
If I use Task.Factory.StartNew without using Thread.Sleep(20) code gets stuck in endless loop.
How can I improve code and get it to work without using Thread.Sleep(20) ?
I tried Task.Factory.StartNew specifying TaskScheduler but that caused code to hang too.
First, don't use
StartNew
. It's dangerous. UseTask.Run
instead.Second, the reason you're seeing and endless loop is that
Task.Delay
just starts a timer and returns a task that completes when that timer fires. If you want the code to actually wait for the timer, then you need toawait
that task. Also,EventStatus
is being accessed from multiple threads without protection, which is not good. You'll need to add a lock to fix this permanently:As a final note, I would get rid of this entirely. Instead of polling for
EventStatus
to change, make it an actual "signal". E.g., assumingEventStatus
is set once, then aTaskCompletionSource<bool>
would work fine.