AsyncLock icon indicating copy to clipboard operation
AsyncLock copied to clipboard

Don't marshal async continuations to the captured context

Open NetherGranite opened this issue 1 month ago • 2 comments

Currently, async/await continuations and Task.ContinueWith(...) continuations are marshalled back to the captured context (TaskScheduler or SynchronizationContext) as is the default behavior with these tools. I believe there is no reason for this in this library. An example of this is if I use this library in an ASP.NET Core web project currently, this library will post its continuations to the web framework's single-threaded UI synchronization context, resulting in worse performance and even deadlocks if asynchronous code is blocked on.

This resolves the issue by 1) using Task.ConfigureAwait(false) in async/await code to instruct the async state machines to schedule continuations onto the default thread pool and 2) passing TaskScheduler.Default to Task.ContinueWith(...) calls to ensure the continuations are run on the default thread pool.

Notably, Task.Run(...) schedules work onto the default thread pool by default, so no changes are needed there. Only continuations are subject to this "marshalling onto the captured context" behavior by default.

Resolves #17.

NetherGranite avatar Jul 01 '24 18:07 NetherGranite