CefSharp.MinimalExample/CefSharp.MinimalExample.OffScreen/SingleThreadSynchronizationContext.cs
Alex Maitland a5d2bbe145 OffScreen - Add async example
- Old example is still there for reference, just not used by default
- Add AsyncContext/SingleThreadSynchronizationContext to ensure async calls continue on main thread.
2021-11-15 16:38:26 +10:00

33 lines
969 B
C#

/// https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace CefSharp.MinimalExample.OffScreen
{
public sealed class SingleThreadSynchronizationContext : SynchronizationContext
{
private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> queue =
new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>();
public override void Post(SendOrPostCallback d, object state)
{
queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state));
}
public void RunOnCurrentThread()
{
while (queue.TryTake(out var workItem, Timeout.Infinite))
{
workItem.Key(workItem.Value);
}
}
public void Complete()
{
queue.CompleteAdding();
}
}
}