Created
June 16, 2020 08:39
-
-
Save kevingosse/7be5b87a4a4e68426ff45e0c89e92bf5 to your computer and use it in GitHub Desktop.
This file contains 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
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