While trying to figure out the new (maybe not so new now, but new to me, anyway) Task
asynchronous programming in C#, I ran into a problem that took me a bit to fig
You should avoid using Task.Factory.StartNew
with async-await. You should use Task.Run
instead.
An async method returns a Task
, an async delegate does as well. Task.Factory.StartNew
also returns a Task
, where its result is the result of the delegate parameter. So when used together it returns a Task
.
All that this Task
does is execute the delegate until there's a task to return, which is when the first await is reached. If you only wait for that task to complete you aren't waiting for the whole method, just the part before the first await.
You can fix that by using Task.Unwrap
which creates a Task
that represents that Task
:
Task wrapperTask = Task.Factory.StartNew(...);
Task actualTask = wrapperTask.Unwrap();
Task.WaitAll(actualTask);