forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncOperationTests.cs
More file actions
216 lines (182 loc) · 8.71 KB
/
AsyncOperationTests.cs
File metadata and controls
216 lines (182 loc) · 8.71 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.ComponentModel.EventBasedAsync.Tests
{
public class AsyncOperationTests
{
private const int SpinTimeoutSeconds = 30;
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Noop()
{
// Test that a simple AsyncOperation can be dispatched and completed via AsyncOperationManager
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
Assert.True(operation.Completed);
Assert.False(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThrowAfterAsyncComplete()
{
Task.Run(() =>
{
var operation = new TestAsyncOperation(op => { });
operation.Wait();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.AsyncOperation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThrowAfterSynchronousComplete()
{
Task.Run(() =>
{
var operation = AsyncOperationManager.CreateOperation(null);
operation.OperationCompleted();
SendOrPostCallback noopCallback = state => { };
Assert.Throws<InvalidOperationException>(() => operation.Post(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.PostOperationCompleted(noopCallback, null));
Assert.Throws<InvalidOperationException>(() => operation.OperationCompleted());
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Cancel()
{
// Test that cancellation gets passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var cancelEvent = new ManualResetEventSlim();
var operation = new TestAsyncOperation(op =>
{
Assert.True(cancelEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
}, cancelEvent: cancelEvent);
operation.Cancel();
operation.Wait();
Assert.True(operation.Completed);
Assert.True(operation.Cancelled);
Assert.Null(operation.Exception);
}).GetAwaiter().GetResult();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void Throw()
{
// Test that exceptions get passed all the way through PostOperationCompleted(callback, AsyncCompletedEventArgs)
Task.Run(() =>
{
var operation = new TestAsyncOperation(op =>
{
throw new TestException("Test throw");
});
Assert.Throws<TestException>(() => operation.Wait());
}).GetAwaiter().GetResult();
}
[Fact]
public static void PostNullDelegate()
{
// the xUnit SynchronizationContext - AysncTestSyncContext interferes with the current SynchronizationContext
// used by AsyncOperation when there is exception thrown -> the SC.OperationCompleted() is not called.
// use new SC here to avoid this issue
var orignal = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
// Pass a non-null state just to emphasize we're only testing passing a null delegate
var state = new object();
var operation = AsyncOperationManager.CreateOperation(state);
Assert.Throws<ArgumentNullException>(() => operation.Post(null, state));
Assert.Throws<ArgumentNullException>(() => operation.PostOperationCompleted(null, state));
}
finally
{
SynchronizationContext.SetSynchronizationContext(orignal);
}
}
// A simple wrapper for AsyncOperation which executes the specified delegate and a completion handler asynchronously.
public class TestAsyncOperation
{
private readonly object _operationId;
private readonly Action<TestAsyncOperation> _executeDelegate;
private readonly ManualResetEventSlim _cancelEvent;
private readonly ManualResetEventSlim _completeEvent;
public AsyncOperation AsyncOperation { get; private set; }
public bool Completed { get { return _completeEvent.IsSet; } }
public bool Cancelled { get { return _cancelEvent.IsSet; } }
public Exception Exception { get; private set; }
public TestAsyncOperation(Action<TestAsyncOperation> executeDelegate, ManualResetEventSlim cancelEvent = null)
{
// Create an async operation passing an object as the state so we can
// verify that state is passed properly.
_operationId = new object();
AsyncOperation = AsyncOperationManager.CreateOperation(_operationId);
Assert.Same(_operationId, AsyncOperation.UserSuppliedState);
Assert.Same(AsyncOperationManager.SynchronizationContext, AsyncOperation.SynchronizationContext);
_completeEvent = new ManualResetEventSlim(false);
_cancelEvent = cancelEvent ?? new ManualResetEventSlim(false);
// Post work to the wrapped synchronization context
_executeDelegate = executeDelegate;
AsyncOperation.Post((SendOrPostCallback)ExecuteWorker, _operationId);
}
public void Wait()
{
Assert.True(_completeEvent.Wait(TimeSpan.FromSeconds(SpinTimeoutSeconds)));
if (Exception != null)
{
throw Exception;
}
}
public void Cancel()
{
CompleteOperationAsync(cancelled: true);
}
private void ExecuteWorker(object operationId)
{
Assert.Same(_operationId, operationId);
Exception exception = null;
try
{
_executeDelegate(this);
}
catch (Exception e)
{
exception = e;
}
finally
{
CompleteOperationAsync(exception: exception);
}
}
private void CompleteOperationAsync(Exception exception = null, bool cancelled = false)
{
if (!(Completed || Cancelled))
{
AsyncOperation.PostOperationCompleted(
(SendOrPostCallback)OnOperationCompleted,
new AsyncCompletedEventArgs(
exception,
cancelled,
_operationId));
}
}
private void OnOperationCompleted(object state)
{
AsyncCompletedEventArgs e = Assert.IsType<AsyncCompletedEventArgs>(state);
Assert.Equal(_operationId, e.UserState);
Exception = e.Error;
// Make sure to set _cancelEvent before _completeEvent so that anyone waiting on
// _completeEvent will not be at risk of reading Cancelled before it is set.
if (e.Cancelled)
_cancelEvent.Set();
_completeEvent.Set();
}
}
}
}