var context = new SingleThreadSynchronizationContext();
context.Post(...);
context.Post(...);
context.Post(...);
context.Complete();
context.RunAll();
Last active
July 9, 2018 08:17
-
-
Save devlights/f17d2d93977411a346a1dedca0f46bee to your computer and use it in GitHub Desktop.
[C#] シングルスレッドで動く SynchronizationContext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment