Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Last active July 5, 2020 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfowl/60a66cf8d543d8ba7829f7e972760649 to your computer and use it in GitHub Desktop.
Save davidfowl/60a66cf8d543d8ba7829f7e972760649 to your computer and use it in GitHub Desktop.
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