CSharp · Console
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
static async Task IdentifyAsync(Task task, int id)
{
await task;
var thread = Thread.CurrentThread;
string name = thread.IsThreadPoolThread
? "Thread pool" : thread.Name;
if (string.IsNullOrEmpty(name))
name = "#" + thread.ManagedThreadId;
Console.WriteLine("Continuation #" + id + " on: " + name + ", id: " + Thread.CurrentThread.ManagedThreadId);
}
public static void Main()
{
Thread.CurrentThread.Name = "Main thread";
Console.WriteLine("Started on: " + Thread.CurrentThread.Name + ", id: " + Thread.CurrentThread.ManagedThreadId);
var source1 = new TaskCompletionSource<int>();
IdentifyAsync(source1.Task, 1);
source1.SetResult(123);
var source2 = new TaskCompletionSource<int>();
IdentifyAsync(source2.Task, 2);
source2.SetResultAsync(123);
Console.WriteLine("Press [return]");
Console.ReadLine();
}
}
public static class TaskExt
{
static public void SetResultAsync<T>(this TaskCompletionSource<T> tcs, T result)
{
FakeSynchronizationContext.Execute(() => tcs.SetResult(result));
}
// FakeSynchronizationContext
class FakeSynchronizationContext : SynchronizationContext
{
private static readonly ThreadLocal<FakeSynchronizationContext> s_context =
new ThreadLocal<FakeSynchronizationContext>(() => new FakeSynchronizationContext());
private FakeSynchronizationContext() { }
public static FakeSynchronizationContext Instance { get { return s_context.Value; } }
public static void Execute(Action action)
{
var savedContext = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(FakeSynchronizationContext.Instance);
try
{
action();
}
finally
{
SynchronizationContext.SetSynchronizationContext(savedContext);
}
}
// SynchronizationContext methods
public override SynchronizationContext CreateCopy()
{
return this;
}
public override void OperationStarted()
{
throw new NotImplementedException("OperationStarted");
}
public override void OperationCompleted()
{
throw new NotImplementedException("OperationCompleted");
}
public override void Post(SendOrPostCallback d, object state)
{
throw new NotImplementedException("Post");
}
public override void Send(SendOrPostCallback d, object state)
{
throw new NotImplementedException("Send");
}
}
}