Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active July 9, 2018 08:17
Show Gist options
  • Save devlights/f17d2d93977411a346a1dedca0f46bee to your computer and use it in GitHub Desktop.
Save devlights/f17d2d93977411a346a1dedca0f46bee to your computer and use it in GitHub Desktop.
[C#] シングルスレッドで動く SynchronizationContext
/// <summary>
/// REF: https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/
/// REF: https://qiita.com/ousttrue/items/66def43267329bc132ff
/// </summary>
internal sealed class SingleThreadSynchronizationContext : SynchronizationContext
{
private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> _queue;
public SingleThreadSynchronizationContext()
{
this._queue = new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>();
}
public override void Post(SendOrPostCallback d, object state)
{
this._queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state));
}
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException();
}
public void RunAll()
{
foreach (var item in this._queue.GetConsumingEnumerable())
{
item.Key(item.Value);
}
}
public void Complete()
{
this._queue.CompleteAdding();
}
}
var context = new SingleThreadSynchronizationContext();

context.Post(...);
context.Post(...);
context.Post(...);

context.Complete();
context.RunAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment