Last active
July 5, 2020 05:51
-
-
Save davidfowl/60a66cf8d543d8ba7829f7e972760649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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