CSharp · Console
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
#nullable enable
public class Program
{
public static async Task Main()
{
using var dispatcher = SimpleDispatcher.StartNew();
var task1 = dispatcher.SendAsync(async () =>
{
Console.WriteLine($"Task 1: Thread {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(100);
Console.WriteLine($"Task 1: Thread {Thread.CurrentThread.ManagedThreadId}");
});
var task2 = dispatcher.SendAsync(async () =>
{
Console.WriteLine($"Task 2: Thread {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(100);
Console.WriteLine($"Task 2: Thread {Thread.CurrentThread.ManagedThreadId}");
});
await Task.WhenAll(task1, task2);
Console.WriteLine("All tasks complete");
}
}
public class SimpleDispatcher : IDisposable
{
private readonly BlockingCollection<QueueItem> queue = new();
private readonly CancellationTokenSource disposeCts = new();
private readonly Thread thread;
public SimpleDispatcher()
{
thread = new Thread(Run);
}
public static SimpleDispatcher StartNew()
{
var dispatcher = new SimpleDispatcher();
dispatcher.Start();
return dispatcher;
}
public void Start()
{
if (thread.IsAlive)
throw new InvalidOperationException("Already running");
thread.Start();
}
public void Post(SendOrPostCallback callback, object? state)
{
var item = new QueueItem
{
Delegate = () =>
{
callback(state);
return Task.CompletedTask;
},
Tcs = new(),
};
queue.Add(item);
// Re-throw any resulting exceptions on the ThreadPool
async void RethrowExceptions()
{
await item.Tcs.Task;
}
RethrowExceptions();
}
public void Send(SendOrPostCallback callback, object? state)
{
var item = new QueueItem
{
Delegate = () =>
{
callback(state);
return Task.CompletedTask;
},
Tcs = new(),
};
queue.Add(item);
item.Tcs.Task.Unwrap().GetAwaiter().GetResult();
}
public Task SendAsync(Func<Task> func)
{
var item = new QueueItem
{
Delegate = func,
Tcs = new(),
};
queue.Add(item);
return item.Tcs.Task.Unwrap();
}
private void Run()
{
SynchronizationContext.SetSynchronizationContext(new SimpleDispatcherSynchronizationContext(this));
try
{
while (true)
{
var item = queue.Take(this.disposeCts.Token);
try
{
var task = item.Delegate();
item.Tcs.SetResult(task);
}
catch (Exception e)
{
item.Tcs.SetException(e);
}
}
}
catch (OperationCanceledException) { }
}
public void Dispose()
{
disposeCts.Cancel();
}
private struct QueueItem
{
public Func<Task> Delegate;
// When complete, the message has been processed, and the TCS contains the Task returned by Delegate
public TaskCompletionSource<Task> Tcs;
}
}
public class SimpleDispatcherSynchronizationContext : SynchronizationContext
{
private readonly SimpleDispatcher dispatcher;
public SimpleDispatcherSynchronizationContext(SimpleDispatcher dispatcher) => this.dispatcher = dispatcher;
public override void Send(SendOrPostCallback d, object? state)
{
dispatcher.Send(d, state);
}
public override void Post(SendOrPostCallback d, object? state)
{
dispatcher.Post(d, state);
}
public override SynchronizationContext CreateCopy() => new SimpleDispatcherSynchronizationContext(dispatcher);
}