Skip to content

Commit

Permalink
Support DispatcherQueueSynchronizationContext.Send.
Browse files Browse the repository at this point in the history
  • Loading branch information
jlaanstra committed Jan 14, 2022
1 parent d1642c8 commit 5c1b45b
Showing 1 changed file with 50 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -1,38 +1,51 @@
using System;
using System.Threading;
using Microsoft.System;

namespace Microsoft.System
{
/// <summary>
/// DispatcherQueueSyncContext allows developers to await calls and get back onto the
/// UI thread. Needs to be installed on the UI thread through DispatcherQueueSyncContext.SetForCurrentThread
/// </summary>
public class DispatcherQueueSynchronizationContext : SynchronizationContext
{
private readonly DispatcherQueue m_dispatcherQueue;

public DispatcherQueueSynchronizationContext(DispatcherQueue dispatcherQueue)
{
m_dispatcherQueue = dispatcherQueue;
}

public override void Post(SendOrPostCallback d, object state)
{
if (d == null)
throw new ArgumentNullException(nameof(d));

m_dispatcherQueue.TryEnqueue(() => d(state));
}

public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("Send not supported");
}

public override SynchronizationContext CreateCopy()
{
return new DispatcherQueueSynchronizationContext(m_dispatcherQueue);
}
}
using System;
using System.Threading;
using Microsoft.System;

namespace Microsoft.System
{
/// <summary>
/// DispatcherQueueSyncContext allows developers to await calls and get back onto the
/// UI thread. Needs to be installed on the UI thread through DispatcherQueueSyncContext.SetForCurrentThread
/// </summary>
public class DispatcherQueueSynchronizationContext : SynchronizationContext
{
private readonly DispatcherQueue m_dispatcherQueue;

public DispatcherQueueSynchronizationContext(DispatcherQueue dispatcherQueue)
{
m_dispatcherQueue = dispatcherQueue;
}

public override void Post(SendOrPostCallback d, object state)
{
if (d == null)
throw new ArgumentNullException(nameof(d));

m_dispatcherQueue.TryEnqueue(() => d(state));
}

public override void Send(SendOrPostCallback d, object state)
{
if (m_dispatcherQueue.HasThreadAccess)
{
d(state);
}
else
{
var m = new ManualResetEvent(false);
m_dispatcherQueue.TryEnqueue(() =>
{
d(state);
m.Set();
});
m.WaitOne();
}
}

public override SynchronizationContext CreateCopy()
{
return new DispatcherQueueSynchronizationContext(m_dispatcherQueue);
}
}
}

0 comments on commit 5c1b45b

Please sign in to comment.