Open djee-ms opened 4 years ago
TaskCompletionSource type has a very peculiar behavior: by default, when SetResult method is called then all the task’s “async” continuations are invoked … synchronously.
+1.
I've been burnt by this in the past in my own library. The approach below has fixed the deadlocks I discovered.
TaskCompletionSource<bool> transferAccepted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Currently some C# async calls like
SetRemoteDescriptionAsync()
(see #195) are spawing a backgroundTask
and inside it waiting on an event to wait from a completion signal from the C interop layer. This This wait is often achieved withManualResetEventSlim
, which blocks the thread executing the task.Instead, we should leverage
TaskCompletionSource
, which acts as a promise for the result of the task, and avoids blocking any thread while waiting for the low-level work completion. https://stackoverflow.com/questions/15316613/when-should-taskcompletionsourcet-be-used https://stackoverflow.com/questions/38996593/promise-equivalent-in-c-sharpNote the caveat that this can create deadlocks, and the use of
TaskContinuationOptions
to work around those cases:https://devblogs.microsoft.com/premier-developer/the-danger-of-taskcompletionsourcet-class/