Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,38 +1,68 @@
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.Runtime.ExceptionServices;
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);
ExceptionDispatchInfo edi = null;

m_dispatcherQueue.TryEnqueue(() =>
{
try
{
d(state);
}
catch (Exception ex)
{
edi = ExceptionDispatchInfo.Capture(ex);
}
finally
{
m.Set();
}
});
m.WaitOne();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure the Send method is allowed to block until the callback runs; it can lead to deadlocks.


#pragma warning disable CA1508 // Avoid dead conditional code
edi?.Throw();
#pragma warning restore CA1508 // Avoid dead conditional code
}
}

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