Skip to content

Instantly share code, notes, and snippets.

@davidfowl

davidfowl/lookbrad.cs

Last active Jul 5, 2020
Embed
What would you like to do?
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp25
{
class Program
{
static async Task Main(string[] args)
{
SynchronizationContext.SetSynchronizationContext(new MySyncContext());
var l = new AsyncLocal<int>
{
Value = 10
};
await Task.Delay(1000);
Console.WriteLine(l.Value);
}
}
public class MySyncContext : SynchronizationContext
{
private readonly Thread _thread;
private readonly BlockingCollection<(SendOrPostCallback d, object state)> _queue = new BlockingCollection<(SendOrPostCallback d, object state)>();
public MySyncContext()
{
_thread = new Thread(Work) { IsBackground = true };
_thread.Start();
}
private void Work(object obj)
{
foreach (var item in _queue.GetConsumingEnumerable())
{
item.d(item.state);
}
}
public override void Post(SendOrPostCallback d, object state)
{
_queue.Add((d, state));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment