I often see recommended for async library code, that we should use ConfigureAwait(false)
on all async calls to avoid situations where the return of our call will be
Synchronization Context is similar to static variable and changing it without restoring before control leaves your method will lead to unexpected behavior.
I don't believe you can safely set current thread's synchronization context inside library function that await
anything as restoring context in the middle of compiler generated code is not really possible to my knowledge.
Sample:
async Task MyLibraryMethodAsync()
{
SynchronizationContext.SetSynchronizationContext(....);
await SomeInnerMethod(); // note that method returns at this point
// maybe restore synchronization context here...
return 42;
}
...
// code that uses library, runs on UI thread
void async OnButtonClick(...)
{
// <-- context here is UI-context, code running on UI thread
Task doSomething = MyLibraryMethodAsync();
// <-- context here is set by MyLibraryMethod - i.e. null, code running on UI thread
var textFromFastService = await FastAsync();
// <-- context here is set by MyLibraryMethod, code running on pool thread (non-UI)
textBox7.Text = textFromFastService; // fails...
var get42 = await doSomething;
}