As JSteward explain in their answer, the first line of code is wrong. It doesn't do what you expect it to do:
Task<Task> task = Task.Factory.StartNew(() => service.StartAsync(ct), ct); // Buggy
The second line has the correct behavior, but not because of the async/await. The async/await can be safely elided. What makes it correct is the Unwrap
. It is still problematic though, because it violates the guideline CA2008 about not creating tasks without passing a TaskScheduler
.
The best way to solve your problem is to use the Task.Run
method:
Task task = Task.Run(() => service.StartAsync(ct), ct); // Correct
You can read about the differences between Task.Run
and Task.Factory.StartNew
in this article by Stephen Toub.