I have a block of code that's roughly like:
async Task Initialize(){
await TaskScheduler.Default;
var service = await CreateServiceAsync();
await TaskScheduler.Default;
var status = await service.CheckStatusAsync();
// ...
}
What purpose does awaiting TaskScheduler.Default
serve if we're not using the task scheduler to schedule anything? What might I break if I remove them?
This is in the startup code for a Visual Studio Extension (VSIX) project.
Normally, task schedulers cannot be await
ed. However, the VS SDK does have some extensions that allow awaiting task schedulers. According to the docs, they are used as "switching" calls so that the async
method just resumes executing on the specified TaskScheduler
.
TaskScheduler.Default
uses the thread pool for continuations, so await TaskScheduler.Default
will change to a thread pool thread for the remainder of the method.
Personally, I don't like "switching" methods, primarily because it's possible to not know what context you're in, e.g., in a catch
block. I prefer using Task.Run
to explicitly scope the work that is done on the thread pool.