forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleThreadSynchronizationContext.cs
More file actions
69 lines (60 loc) · 1.82 KB
/
SingleThreadSynchronizationContext.cs
File metadata and controls
69 lines (60 loc) · 1.82 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
62
63
64
65
66
67
68
69
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Npgsql
{
sealed class SingleThreadSynchronizationContext : SynchronizationContext, IDisposable
{
readonly BlockingCollection<CallbackAndState> _tasks = new BlockingCollection<CallbackAndState>();
Thread? _thread;
const int ThreadStayAliveMs = 10000;
readonly string _threadName;
internal SingleThreadSynchronizationContext(string threadName)
=> _threadName = threadName;
public override void Post(SendOrPostCallback callback, object? state)
{
_tasks.Add(new CallbackAndState { Callback = callback, State = state });
if (_thread == null)
{
lock (this)
{
if (_thread != null)
return;
_thread = new Thread(WorkLoop) { Name = _threadName, IsBackground = true };
_thread.Start();
}
}
}
public void Dispose()
{
_tasks.CompleteAdding();
_tasks.Dispose();
lock (this)
{
_thread?.Join();
}
}
void WorkLoop()
{
try
{
while (true)
{
var taken = _tasks.TryTake(out var callbackAndState, ThreadStayAliveMs);
if (!taken)
return;
callbackAndState.Callback(callbackAndState.State);
}
}
finally
{
lock (this) { _thread = null; }
}
}
struct CallbackAndState
{
internal SendOrPostCallback Callback;
internal object? State;
}
}
}