Consider the following code:
public Task SomeAsyncMethod() { var tcs = new TaskCompletionSource(); ... do something, NOT setting the TaskCompletionSource... return tcs.Task } public void Callsite1() { await SomeAsyncMethod(); Debug.WriteLine(Thread.CurrentThread.ManagedThreadId); } public void Callsite2() { SomeAsyncMethod().ContinueWith((task) => { Debug.WriteLine(Thread.CurrentThread.ManagedThreadId); }); }
At some point in time, the TaskCompletion source created in SomeAsyncMethod is installed in ThreadPool Thread:
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId); tcs.SetResult();
When Task expects from a TaskCompletionSource object (as in Callsite1), the continuation is performed synchronously in a thread called SetResult. When ContinueWith is called (as in Callsite2), the continuation is performed asynchronously in another thread.
This does not help call configure wait, as in
public void Callsite1() { await SomeAsyncMethod().ConfigureAwait(true or false); }
and itβs not even a question of this question. As a developer of SomeAsyncMethod, I don't want to call some potentially unknown code by calling SetResult. I want the continuation to always be scheduled asynchronously. And I canβt rely on the caller to properly configure the wait (if that even works).
How to configure TaskCompletionSource so that its task does not execute its continuation synchronously when it was waiting?
source share