-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.CurrentThreadSynchronizationContext.cs
More file actions
61 lines (55 loc) · 2.22 KB
/
Program.CurrentThreadSynchronizationContext.cs
File metadata and controls
61 lines (55 loc) · 2.22 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;
namespace CSharpScriptRunner
{
static partial class Program
{
sealed class SynchronizationContextScope : IDisposable
{
readonly SynchronizationContext _syncCtx;
bool _isDisposed = true;
public SynchronizationContextScope() => _syncCtx = SynchronizationContext.Current;
public void Install(SynchronizationContext synchronizationContext)
{
Dispose();
SynchronizationContext.SetSynchronizationContext(synchronizationContext);
_isDisposed = false;
}
public System.Runtime.CompilerServices.YieldAwaitable InstallAndYield(SynchronizationContext synchronizationContext)
{
Install(synchronizationContext);
return Task.Yield();
}
public void Dispose()
{
if (_isDisposed)
return;
_isDisposed = true;
var current = SynchronizationContext.Current;
if (current == _syncCtx)
return;
if (current is IDisposable disposable)
disposable.Dispose();
SynchronizationContext.SetSynchronizationContext(_syncCtx);
}
}
sealed class CurrentThreadSynchronizationContext : System.Threading.SynchronizationContext, IDisposable
{
readonly BlockingCollection<(SendOrPostCallback Callback, object State)> _queue = new();
int _isRunning;
public CurrentThreadSynchronizationContext() { }
public override void Send(SendOrPostCallback d, object state) => throw new InvalidOperationException();
public override void Post(SendOrPostCallback d, object state)
{
_queue.Add((d, state));
if (Interlocked.Exchange(ref _isRunning, 1) != 0)
return;
foreach (var item in _queue.GetConsumingEnumerable())
item.Callback(item.State);
}
public void Dispose() => _queue.CompleteAdding();
}
}
}