Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevingosse/7be5b87a4a4e68426ff45e0c89e92bf5 to your computer and use it in GitHub Desktop.
Save kevingosse/7be5b87a4a4e68426ff45e0c89e92bf5 to your computer and use it in GitHub Desktop.
public class SingleThreadedSynchronizationContext : SynchronizationContext
{
private Thread _thread;
private BlockingCollection<Action> _queue = new BlockingCollection<Action>();
public SingleThreadedSynchronizationContext()
{
_thread = new Thread(() =>
{
SynchronizationContext.SetSynchronizationContext(this);
foreach (var callback in _queue.GetConsumingEnumerable())
{
callback();
}
});
_thread.Start();
}
public override void Post(SendOrPostCallback d, object state)
{
_queue.Add(() => d(state));
}
public override void Send(SendOrPostCallback d, object state)
{
using (var mutex = new ManualResetEventSlim())
{
_queue.Add(() =>
{
d(state);
mutex.Set();
});
mutex.Wait();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment