Skip to content

Instantly share code, notes, and snippets.

@NtFreX
Created May 22, 2018 11:20
Show Gist options
  • Save NtFreX/499ef209be928439c9ef842e353b4fc5 to your computer and use it in GitHub Desktop.
Save NtFreX/499ef209be928439c9ef842e353b4fc5 to your computer and use it in GitHub Desktop.
public class MessagePumpDispatcher : IDisposable
{
private readonly ManualResetEventSlim _creatingThreadComplete;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly Thread _thread;
private Dispatcher _dispatcher;
public MessagePumpDispatcher()
{
_creatingThreadComplete = new ManualResetEventSlim(false);
_cancellationTokenSource = new CancellationTokenSource();
_thread = new Thread(RunThread);
_thread.SetApartmentState(ApartmentState.STA);
_thread.IsBackground = true;
_thread.Start();
}
private void RunThread()
{
_dispatcher = Dispatcher.CurrentDispatcher;
_creatingThreadComplete.Set();
try
{
Dispatcher.Run();
}
catch (ThreadAbortException)
{
Thread.ResetAbort();
}
}
public void Dispatch(Action action)
{
_creatingThreadComplete.Wait(_cancellationTokenSource.Token);
_dispatcher.Invoke(action);
}
public Task<T> DispatchAsync<T>(Func<T> action)
{
_creatingThreadComplete.Wait(_cancellationTokenSource.Token);
var result = _dispatcher.Invoke(action);
return Task.FromResult(result);
}
public Task DispatchAsync(Action action)
{
_creatingThreadComplete.Wait(_cancellationTokenSource.Token);
_dispatcher.Invoke(action);
return Task.CompletedTask;
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_thread.Abort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment