-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
SingleThreadedSynchronizationContext.cs
45 lines (39 loc) · 1.46 KB
/
SingleThreadedSynchronizationContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Microsoft.Extensions.Internal
{
internal class SingleThreadedSynchronizationContext : SynchronizationContext
{
private readonly BlockingCollection<(SendOrPostCallback Callback, object State)> _queue = new BlockingCollection<(SendOrPostCallback Callback, object State)>();
public override void Send(SendOrPostCallback d, object state) // Sync operations
{
throw new NotSupportedException($"{nameof(SingleThreadedSynchronizationContext)} does not support synchronous operations.");
}
public override void Post(SendOrPostCallback d, object state) // Async operations
{
_queue.Add((d, state));
}
public static void Run(Action action)
{
var previous = Current;
var context = new SingleThreadedSynchronizationContext();
SetSynchronizationContext(context);
try
{
action();
while (context._queue.TryTake(out var item))
{
item.Callback(item.State);
}
}
finally
{
context._queue.CompleteAdding();
SetSynchronizationContext(previous);
}
}
}
}