forked from vtortola/WebSocketListener
/
DelegateHelper.cs
202 lines (180 loc) · 7.73 KB
/
DelegateHelper.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
Copyright (c) 2017 Denis Zykov
License: https://opensource.org/licenses/MIT
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using HasSingleTargetFn = System.Predicate<System.MulticastDelegate>;
namespace vtortola.WebSockets.Tools
{
internal static class DelegateHelper
{
private static readonly SendOrPostCallback SendOrPostCallbackRunAction;
#if !NETSTANDARD && !UAP
private static readonly HasSingleTargetFn HasSingleTarget;
private static readonly WaitCallback WaitCallbackRunAction;
#endif
static DelegateHelper()
{
SendOrPostCallbackRunAction = RunAction;
#if !NETSTANDARD && !UAP
const BindingFlags SEARCH_FLAGS = BindingFlags.NonPublic | BindingFlags.Instance;
var hasSingleTargetMethod = typeof(MulticastDelegate).GetMethod("InvocationListLogicallyNull", SEARCH_FLAGS) ??
typeof(MulticastDelegate).GetMethod("get_HasSingleTarget", SEARCH_FLAGS);
if (hasSingleTargetMethod != null) HasSingleTarget = (HasSingleTargetFn)Delegate.CreateDelegate(typeof(HasSingleTargetFn), hasSingleTargetMethod, true);
else // gracefull degradation
HasSingleTarget = md => md.GetInvocationList().Length == 1;
WaitCallbackRunAction = RunAction;
#endif
}
#if !NETSTANDARD && !UAP
public static bool IsSingleTarget(MulticastDelegate @delegate)
{
return HasSingleTarget(@delegate);
}
#endif
public static void InterlockedCombine<DelegateT>(ref DelegateT location, DelegateT value) where DelegateT : class
{
var spinWait = new SpinWait();
var currentValue = Volatile.Read(ref location);
var expectedValue = default(DelegateT);
do
{
expectedValue = currentValue;
var newValue = (DelegateT)(object)Delegate.Combine((Delegate)(object)currentValue, (Delegate)(object)value);
currentValue = Interlocked.CompareExchange(ref location, newValue, expectedValue);
spinWait.SpinOnce();
} while (currentValue != expectedValue);
}
public static bool InterlockedRemove<DelegateT>(ref DelegateT location, DelegateT value) where DelegateT : class
{
var currentValue = Volatile.Read(ref location);
var expectedValue = default(DelegateT);
if (currentValue == null) return false;
var spinWait = new SpinWait();
do
{
expectedValue = currentValue;
var newValue = (DelegateT)(object)Delegate.Remove((Delegate)(object)currentValue, (Delegate)(object)value);
if (newValue == currentValue) return false;
currentValue = Interlocked.CompareExchange(ref location, newValue, expectedValue);
spinWait.SpinOnce();
} while (currentValue != expectedValue);
return true;
}
[SecurityCritical]
internal static void UnsafeQueueContinuation(Action continuation, bool continueOnCapturedContext, bool schedule)
{
if (continuation == null) throw new ArgumentNullException(nameof(continuation));
#if !NETSTANDARD && !UAP
if (!IsSingleTarget(continuation))
{
var runErrors = default(List<Exception>);
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (Action action in continuation.GetInvocationList())
{
try
{
UnsafeQueueContinuation(action, continueOnCapturedContext, schedule);
}
catch (Exception runError)
{
if (runErrors == null) runErrors = new List<Exception>();
runErrors.Add(runError);
}
}
if (runErrors != null)
throw new AggregateException(runErrors);
return;
}
#endif
var currentScheduler = TaskScheduler.Current ?? TaskScheduler.Default;
var syncContext = SynchronizationContext.Current;
var isDefaultSyncContext = syncContext == null || syncContext.GetType() == typeof(SynchronizationContext);
if (schedule && continueOnCapturedContext && syncContext != null && !isDefaultSyncContext)
{
syncContext.Post(SendOrPostCallbackRunAction, continuation);
}
else if (schedule || currentScheduler != TaskScheduler.Default)
{
#if !NETSTANDARD && !UAP
if (currentScheduler == TaskScheduler.Default)
{
ThreadPool.UnsafeQueueUserWorkItem(WaitCallbackRunAction, continuation);
}
else
{
Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.PreferFairness, currentScheduler);
}
#else
Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.PreferFairness, currentScheduler);
#endif
}
else
{
continuation();
}
}
[SecuritySafeCritical]
internal static void QueueContinuation(Action continuation, bool continueOnCapturedContext, bool schedule)
{
if (continuation == null) throw new ArgumentNullException(nameof(continuation));
#if !NETSTANDARD && !UAP
if (!IsSingleTarget(continuation))
{
var runErrors = default(List<Exception>);
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
foreach (Action action in continuation.GetInvocationList())
{
try
{
UnsafeQueueContinuation(action, continueOnCapturedContext, schedule);
}
catch (Exception runError)
{
if (runErrors == null) runErrors = new List<Exception>();
runErrors.Add(runError);
}
}
if (runErrors != null)
throw new AggregateException(runErrors);
return;
}
#endif
var currentScheduler = TaskScheduler.Current ?? TaskScheduler.Default;
var syncContext = SynchronizationContext.Current;
var isDefaultSyncContext = syncContext == null || syncContext.GetType() == typeof(SynchronizationContext);
if (schedule && continueOnCapturedContext && syncContext != null && !isDefaultSyncContext)
{
syncContext.Post(SendOrPostCallbackRunAction, continuation);
}
else if (schedule || currentScheduler != TaskScheduler.Default)
{
#if !NETSTANDARD && !UAP
if (currentScheduler == TaskScheduler.Default)
{
ThreadPool.QueueUserWorkItem(WaitCallbackRunAction, continuation);
}
else
{
Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.PreferFairness, currentScheduler);
}
#else
Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.PreferFairness, currentScheduler);
#endif
}
else
{
continuation();
}
}
private static void RunAction(object state)
{
((Action)state)();
}
}
}