/
AsyncTestSyncContext.cs
116 lines (107 loc) · 3.54 KB
/
AsyncTestSyncContext.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
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Xunit.Sdk
{
/// <summary>
/// This implementation of <see cref="SynchronizationContext"/> allows the developer to track the count
/// of outstanding "async void" operations, and wait for them all to complete.
/// </summary>
public class AsyncTestSyncContext : SynchronizationContext
{
readonly AsyncManualResetEvent @event = new AsyncManualResetEvent(true);
Exception exception;
readonly SynchronizationContext innerContext;
int operationCount;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTestSyncContext"/> class.
/// </summary>
/// <param name="innerContext">The existing synchronization context (may be <c>null</c>).</param>
public AsyncTestSyncContext(SynchronizationContext innerContext)
{
this.innerContext = innerContext;
}
/// <inheritdoc/>
public override void OperationCompleted()
{
var result = Interlocked.Decrement(ref operationCount);
if (result == 0)
@event.Set();
}
/// <inheritdoc/>
public override void OperationStarted()
{
Interlocked.Increment(ref operationCount);
@event.Reset();
}
/// <inheritdoc/>
public override void Post(SendOrPostCallback d, object state)
{
// The call to Post() may be the state machine signaling that an exception is
// about to be thrown, so we make sure the operation count gets incremented
// before the Task.Run, and then decrement the count when the operation is done.
OperationStarted();
try
{
if (innerContext == null)
{
XunitWorkerThread.QueueUserWorkItem(() =>
{
try
{
d(state);
}
catch (Exception ex)
{
exception = ex;
}
finally
{
OperationCompleted();
}
});
}
else
innerContext.Post(_ =>
{
try
{
d(state);
}
catch (Exception ex)
{
exception = ex;
}
finally
{
OperationCompleted();
}
}, null);
}
catch { }
}
/// <inheritdoc/>
public override void Send(SendOrPostCallback d, object state)
{
try
{
if (innerContext != null)
innerContext.Send(d, state);
else
d(state);
}
catch (Exception ex)
{
exception = ex;
}
}
/// <summary>
/// Returns a task which is signaled when all outstanding operations are complete.
/// </summary>
public async Task<Exception> WaitForCompletionAsync()
{
await @event.WaitAsync();
return exception;
}
}
}