Reputation: 78065
When calling SetResult
on a TaskCompletionSource
in C#, is it possible to force the continuations to be called on the same thread, so that SetResult
doesn't return until all continuations have executed?
Example:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
var tcs = new TaskCompletionSource<string>(TaskContinuationOptions.ExecuteSynchronously);
var task = Task.Run(async () =>
{
Console.WriteLine("Awaiting task on thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
await tcs.Task;
Console.WriteLine("Continuation called on thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
});
await Task.Delay(100);
Console.WriteLine("SetResult called on thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
tcs.SetResult("done");
await task;
}
}
Example output:
Awaiting task on thread ID: 11
SetResult called on thread ID: 19
Continuation called on thread ID: 9
If not, is there any other way to await the execution of the continuations of the tcs.Task
after calling SetResult?
The behavior would be similar to calling Invoke
on an event, where each delegate will be executed on the same thread before the Invoke call returns.
In the case a continuation awaits, the expected behavior would be for SetResult
to return as well, and not wait for the full completion of the continuation.
Upvotes: 1
Views: 276