-
Notifications
You must be signed in to change notification settings - Fork 148
/
JoinableTaskTests.cs
3681 lines (3188 loc) · 144 KB
/
JoinableTaskTests.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Microsoft.VisualStudio.Threading.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xunit;
using Xunit.Abstractions;
public class JoinableTaskTests : JoinableTaskTestBase
{
public JoinableTaskTests(ITestOutputHelper logger)
: base(logger)
{
}
[StaFact]
public void RunFuncOfTaskSTA()
{
this.RunFuncOfTaskHelper();
}
[StaFact]
public void RunFuncOfTaskMTA()
{
Task.Run(() => this.RunFuncOfTaskHelper()).Wait();
}
[StaFact]
public void RunFuncOfTaskOfTSTA()
{
this.RunFuncOfTaskOfTHelper();
}
[StaFact]
public void RunFuncOfTaskOfTMTA()
{
Task.Run(() => this.RunFuncOfTaskOfTHelper()).GetAwaiter().GetResult();
}
[StaFact]
public void LeaveAndReturnToSTA()
{
var fullyCompleted = false;
this.asyncPump.Run(async delegate
{
Assert.Same(this.originalThread, Thread.CurrentThread);
await TaskScheduler.Default;
Assert.NotSame(this.originalThread, Thread.CurrentThread);
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
fullyCompleted = true;
});
Assert.True(fullyCompleted);
}
[StaFact]
public void SwitchToMainThreadDoesNotYieldWhenAlreadyOnMainThread()
{
Assert.True(this.asyncPump.SwitchToMainThreadAsync().GetAwaiter().IsCompleted, "Yield occurred even when already on UI thread.");
}
[StaFact]
public void SwitchToMainThreadYieldsWhenOffMainThread()
{
Task.Run(
() => Assert.False(this.asyncPump.SwitchToMainThreadAsync().GetAwaiter().IsCompleted, "Yield did not occur when off Main thread."))
.GetAwaiter().GetResult();
}
[StaFact]
public void SwitchToMainThreadAsyncContributesToHangReportsAndCollections()
{
var mainThreadRequestPended = new ManualResetEventSlim();
Exception delegateFailure = null;
Task.Run(delegate
{
var awaiter = this.asyncPump.SwitchToMainThreadAsync().GetAwaiter();
awaiter.OnCompleted(delegate
{
try
{
Assert.Same(this.originalThread, Thread.CurrentThread);
}
catch (Exception ex)
{
delegateFailure = ex;
}
finally
{
this.testFrame.Continue = false;
}
});
mainThreadRequestPended.Set();
});
Assert.True(mainThreadRequestPended.Wait(TestTimeout));
// Verify here that pendingTasks includes one task.
Assert.Equal(1, this.GetPendingTasksCount());
Assert.Equal(1, this.joinableCollection.Count());
// Now let the request proceed through.
this.PushFrame();
Assert.Equal(0, this.GetPendingTasksCount());
Assert.Equal(0, this.joinableCollection.Count());
if (delegateFailure != null)
{
throw new TargetInvocationException(delegateFailure);
}
}
[StaFact]
public void SwitchToMainThreadAsyncWithinCompleteTaskGetsNewTask()
{
// For this test, the JoinableTaskFactory we use shouldn't have its own collection.
// This is important for hitting the code path that was buggy before this test was written.
this.joinableCollection = null;
this.asyncPump = new DerivedJoinableTaskFactory(this.context);
var outerTaskCompleted = new AsyncManualResetEvent();
Task innerTask = null;
this.asyncPump.RunAsync(delegate
{
innerTask = Task.Run(async delegate
{
await outerTaskCompleted;
// This thread transition runs within the context of a completed task.
// In this transition, the JoinableTaskFactory should create a new, incompleted
// task to represent the transition.
// This is verified by our DerivedJoinableTaskFactory which will throw if
// the task has already completed.
await this.asyncPump.SwitchToMainThreadAsync();
});
return TplExtensions.CompletedTask;
});
outerTaskCompleted.Set();
innerTask.ContinueWith(_ => this.testFrame.Continue = false);
// Now let the request proceed through.
this.PushFrame();
innerTask.Wait(); // rethrow exceptions
}
[StaFact]
public void SwitchToMainThreadAsyncTwiceRemainsInJoinableCollection()
{
((DerivedJoinableTaskFactory)this.asyncPump).AssumeConcurrentUse = true;
var mainThreadRequestPended = new ManualResetEventSlim();
Exception delegateFailure = null;
Task.Run(delegate
{
this.asyncPump.RunAsync(
delegate
{
var awaiter = this.asyncPump.SwitchToMainThreadAsync().GetAwaiter();
awaiter.OnCompleted(
delegate
{
try
{
Assert.Same(this.originalThread, Thread.CurrentThread);
}
catch (Exception ex)
{
delegateFailure = ex;
}
finally
{
this.testFrame.Continue = false;
}
});
awaiter.OnCompleted(
delegate
{
try
{
Assert.Same(this.originalThread, Thread.CurrentThread);
}
catch (Exception ex)
{
delegateFailure = ex;
}
finally
{
this.testFrame.Continue = false;
}
});
return TplExtensions.CompletedTask;
});
mainThreadRequestPended.Set();
});
Assert.True(mainThreadRequestPended.Wait(TestTimeout));
// Verify here that pendingTasks includes one task.
Assert.Equal(1, ((DerivedJoinableTaskFactory)this.asyncPump).TransitioningTasksCount);
// Now let the request proceed through.
this.PushFrame();
this.testFrame.Continue = true; // reset for next time
// Verify here that pendingTasks includes one task.
Assert.Equal(1, ((DerivedJoinableTaskFactory)this.asyncPump).TransitioningTasksCount);
// Now let the request proceed through.
this.PushFrame();
Assert.Equal(0, ((DerivedJoinableTaskFactory)this.asyncPump).TransitioningTasksCount);
if (delegateFailure != null)
{
throw new TargetInvocationException(delegateFailure);
}
}
[StaFact]
public void SwitchToMainThreadAsyncTransitionsCanSeeAsyncLocals()
{
var mainThreadRequestPended = new ManualResetEventSlim();
Exception delegateFailure = null;
var asyncLocal = new AsyncLocal<object>();
var asyncLocalValue = new object();
// The point of this test is to verify that the transitioning/transitioned
// methods on the JoinableTaskFactory can see into the AsyncLocal<T>.Value
// as defined in the context that is requesting the transition.
// The ProjectLockService depends on this behavior to identify UI thread
// requestors that hold a project lock, on both sides of the transition.
((DerivedJoinableTaskFactory)this.asyncPump).TransitioningToMainThreadCallback =
jt => { Assert.Same(asyncLocalValue, asyncLocal.Value); };
((DerivedJoinableTaskFactory)this.asyncPump).TransitionedToMainThreadCallback =
jt => { Assert.Same(asyncLocalValue, asyncLocal.Value); };
Task.Run(delegate
{
asyncLocal.Value = asyncLocalValue;
var awaiter = this.asyncPump.SwitchToMainThreadAsync().GetAwaiter();
awaiter.OnCompleted(delegate
{
try
{
Assert.Same(this.originalThread, Thread.CurrentThread);
Assert.Same(asyncLocalValue, asyncLocal.Value);
}
catch (Exception ex)
{
delegateFailure = ex;
}
finally
{
this.testFrame.Continue = false;
}
});
mainThreadRequestPended.Set();
});
Assert.True(mainThreadRequestPended.Wait(Timeout.Infinite));
// Now let the request proceed through.
this.PushFrame();
if (delegateFailure != null)
{
throw new TargetInvocationException(delegateFailure);
}
}
[StaFact]
public void SwitchToMainThreadCancellable()
{
var task = Task.Run(async delegate
{
var cts = new CancellationTokenSource(AsyncDelay);
try
{
await this.asyncPump.SwitchToMainThreadAsync(cts.Token);
Assert.True(false, "Expected OperationCanceledException not thrown.");
}
catch (OperationCanceledException)
{
}
Assert.NotSame(this.originalThread, Thread.CurrentThread);
});
Assert.True(task.Wait(TestTimeout * 3), "Test timed out.");
}
[StaFact]
public void SwitchToMainThreadCancellableWithinRun()
{
var endTestTokenSource = new CancellationTokenSource(AsyncDelay);
try
{
this.asyncPump.Run(delegate
{
using (this.context.SuppressRelevance())
{
return Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync(endTestTokenSource.Token);
});
}
});
Assert.True(false, "Expected OperationCanceledException not thrown.");
}
catch (OperationCanceledException)
{
}
}
/// <summary>
/// Verify that if the <see cref="JoinableTaskContext"/> was initialized
/// without a <see cref="SynchronizationContext"/> whose
/// <see cref="SynchronizationContext.Post"/> method executes its delegate
/// on the <see cref="Thread"/> passed to the <see cref="JoinableTaskContext"/>
/// constructor, that an attempt to switch to the main thread using JTF
/// throws an informative exception.
/// </summary>
[StaFact]
public async Task SwitchToMainThreadThrowsUsefulExceptionIfJTCIsMisconfigured()
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var jtc = new JoinableTaskContext();
await TaskScheduler.Default;
try
{
await jtc.Factory.SwitchToMainThreadAsync();
}
catch (JoinableTaskContextException)
{
}
}
[StaFact]
public void SwitchToSTADoesNotCauseUnrelatedReentrancy()
{
var uiThreadNowBusy = new TaskCompletionSource<object>();
bool contenderHasReachedUIThread = false;
var backgroundContender = Task.Run(async delegate
{
await uiThreadNowBusy.Task;
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
contenderHasReachedUIThread = true;
this.testFrame.Continue = false;
});
this.asyncPump.Run(async delegate
{
uiThreadNowBusy.SetResult(null);
Assert.Same(this.originalThread, Thread.CurrentThread);
await TaskScheduler.Default;
Assert.NotSame(this.originalThread, Thread.CurrentThread);
await Task.Delay(AsyncDelay); // allow ample time for the background contender to re-enter the STA thread if it's possible (we don't want it to be).
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
Assert.False(contenderHasReachedUIThread, "The contender managed to get to the STA thread while other work was on it.");
});
// Pump messages until everything's done.
this.PushFrame();
Assert.True(backgroundContender.Wait(AsyncDelay), "Background contender never reached the UI thread.");
}
[StaFact]
public void SwitchToSTASucceedsForRelevantWork()
{
this.asyncPump.Run(async delegate
{
var backgroundContender = Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
Assert.Same(this.originalThread, Thread.CurrentThread);
await TaskScheduler.Default;
Assert.NotSame(this.originalThread, Thread.CurrentThread);
// We can't complete until this seemingly unrelated work completes.
// This shouldn't deadlock because this synchronous operation kicked off
// the operation to begin with.
await backgroundContender;
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
}
[StaFact]
public void SwitchToSTASucceedsForDependentWork()
{
var uiThreadNowBusy = new TaskCompletionSource<object>();
var backgroundContenderCompletedRelevantUIWork = new TaskCompletionSource<object>();
var backgroundInvitationReverted = new TaskCompletionSource<object>();
bool syncUIOperationCompleted = false;
var backgroundContender = Task.Run(async delegate
{
await uiThreadNowBusy.Task;
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
// Release, then reacquire the STA a couple of different ways
// to verify that even after the invitation has been extended
// to join the STA thread we can leave and revisit.
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
// Now complete the task that the synchronous work is waiting before reverting their invitation.
backgroundContenderCompletedRelevantUIWork.SetResult(null);
// Temporarily get off UI thread until the UI thread has rescinded offer to lend its time.
// In so doing, once the task we're waiting on has completed, we'll be scheduled to return using
// the current synchronization context, which because we switched to the main thread earlier
// and have not yet switched off, will mean our continuation won't execute until the UI thread
// becomes available (without any reentrancy).
await backgroundInvitationReverted.Task;
// We should now be on the UI thread (and the Run delegate below should have altogether completd.)
Assert.Same(this.originalThread, Thread.CurrentThread);
Assert.True(syncUIOperationCompleted); // should be true because continuation needs same thread that this is set on.
});
this.asyncPump.Run(async delegate
{
uiThreadNowBusy.SetResult(null);
Assert.Same(this.originalThread, Thread.CurrentThread);
await TaskScheduler.Default;
Assert.NotSame(this.originalThread, Thread.CurrentThread);
using (this.joinableCollection.Join())
{ // invite the work to re-enter our synchronous work on the STA thread.
await backgroundContenderCompletedRelevantUIWork.Task; // we can't complete until this seemingly unrelated work completes.
} // stop inviting more work from background thread.
await this.asyncPump.SwitchToMainThreadAsync();
var nowait = backgroundInvitationReverted.SetAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
syncUIOperationCompleted = true;
using (this.joinableCollection.Join())
{
// Since this background task finishes on the UI thread, we need to ensure
// it can get on it.
await backgroundContender;
}
});
}
[StaFact]
public void TransitionToMainThreadNotRaisedWhenAlreadyOnMainThread()
{
var factory = (DerivedJoinableTaskFactory)this.asyncPump;
factory.Run(async delegate
{
// Switch to main thread when we're already there.
await factory.SwitchToMainThreadAsync();
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected since we're already on the main thread.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected since we're already on the main thread.");
// While on the main thread, await something that executes on a background thread.
await Task.Run(delegate
{
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected when moving off the main thread.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected when moving off the main thread.");
});
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected since the main thread was ultimately blocked for this job.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected since the main thread was ultimately blocked for this job.");
// Now switch explicitly to a threadpool thread.
await TaskScheduler.Default;
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected when moving off the main thread.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected when moving off the main thread.");
// Now switch back to the main thread.
await factory.SwitchToMainThreadAsync();
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected because the main thread was ultimately blocked for this job.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected because the main thread was ultimately blocked for this job.");
});
}
[StaFact]
[Trait("TestCategory", "FailsInCloudTest")] // see https://github.com/Microsoft/vs-threading/issues/44
public void TransitionToMainThreadRaisedWhenSwitchingToMainThread()
{
var factory = (DerivedJoinableTaskFactory)this.asyncPump;
var joinableTask = factory.RunAsync(async delegate
{
// Switch to main thread when we're already there.
await factory.SwitchToMainThreadAsync();
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected since we're already on the main thread.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected since we're already on the main thread.");
// While on the main thread, await something that executes on a background thread.
await Task.Run(delegate
{
Assert.Equal(0, factory.TransitioningToMainThreadHitCount); //, "No transition expected when moving off the main thread.");
Assert.Equal(0, factory.TransitionedToMainThreadHitCount); //, "No transition expected when moving off the main thread.");
});
Assert.Equal(1, factory.TransitioningToMainThreadHitCount); //, "Reacquisition of main thread should have raised transition events.");
Assert.Equal(1, factory.TransitionedToMainThreadHitCount); //, "Reacquisition of main thread should have raised transition events.");
// Now switch explicitly to a threadpool thread.
await TaskScheduler.Default;
Assert.Equal(1, factory.TransitioningToMainThreadHitCount); // No transition expected when moving off the main thread.
Assert.Equal(1, factory.TransitionedToMainThreadHitCount); // No transition expected when moving off the main thread.
// Now switch back to the main thread.
await factory.SwitchToMainThreadAsync();
Assert.Equal(2, factory.TransitioningToMainThreadHitCount); // Reacquisition of main thread should have raised transition events.
Assert.Equal(2, factory.TransitionedToMainThreadHitCount); // Reacquisition of main thread should have raised transition events.
});
// Simulate the UI thread just pumping ordinary messages
joinableTask.Task.ContinueWith(_ => this.testFrame.Continue = false, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
this.PushFrame();
joinableTask.Join(); // Throw exceptions thrown by the async task.
}
[StaFact]
public void RunSynchronouslyNestedNoJoins()
{
bool outerCompleted = false, innerCompleted = false;
this.asyncPump.Run(async delegate
{
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
this.asyncPump.Run(async delegate
{
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
Assert.Same(this.originalThread, Thread.CurrentThread);
innerCompleted = true;
});
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
outerCompleted = true;
});
Assert.True(innerCompleted, "Nested Run did not complete.");
Assert.True(outerCompleted, "Outer Run did not complete.");
}
[StaFact]
public void RunSynchronouslyNestedWithJoins()
{
bool outerCompleted = false, innerCompleted = false;
this.asyncPump.Run(async delegate
{
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
await this.TestReentrancyOfUnrelatedDependentWork();
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
await this.TestReentrancyOfUnrelatedDependentWork();
Assert.Same(this.originalThread, Thread.CurrentThread);
this.asyncPump.Run(async delegate
{
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
await this.TestReentrancyOfUnrelatedDependentWork();
Assert.Same(this.originalThread, Thread.CurrentThread);
await Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
await this.TestReentrancyOfUnrelatedDependentWork();
Assert.Same(this.originalThread, Thread.CurrentThread);
Assert.Same(this.originalThread, Thread.CurrentThread);
innerCompleted = true;
});
await Task.Yield();
Assert.Same(this.originalThread, Thread.CurrentThread);
outerCompleted = true;
});
Assert.True(innerCompleted, "Nested Run did not complete.");
Assert.True(outerCompleted, "Outer Run did not complete.");
}
[StaFact]
public void RunSynchronouslyOffMainThreadRequiresJoinToReenterMainThreadForSameAsyncPumpInstance()
{
var task = Task.Run(delegate
{
this.asyncPump.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread); //, "We're not on the Main thread!");
});
});
this.asyncPump.Run(async delegate
{
// Even though it's all the same instance of AsyncPump,
// unrelated work (work not spun off from this block) must still be
// Joined in order to execute here.
Assert.NotSame(task, await Task.WhenAny(task, Task.Delay(AsyncDelay / 2))); //, "The unrelated main thread work completed before the Main thread was joined.");
using (this.joinableCollection.Join())
{
this.PrintActiveTasksReport();
await task;
}
});
}
[StaFact]
public void RunSynchronouslyOffMainThreadRequiresJoinToReenterMainThreadForDifferentAsyncPumpInstance()
{
var otherCollection = this.context.CreateCollection();
var otherAsyncPump = this.context.CreateFactory(otherCollection);
var task = Task.Run(delegate
{
otherAsyncPump.Run(async delegate
{
await otherAsyncPump.SwitchToMainThreadAsync();
Assert.Same(this.originalThread, Thread.CurrentThread);
});
});
this.asyncPump.Run(async delegate
{
Assert.NotSame(task, await Task.WhenAny(task, Task.Delay(AsyncDelay / 2))); //, "The unrelated main thread work completed before the Main thread was joined.");
using (otherCollection.Join())
{
await task;
}
});
}
/// <summary>
/// Checks that posting to the SynchronizationContext.Current doesn't cause a hang.
/// </summary>
/// <remarks>
/// DevDiv bug 874540 represents a hang that this test repros.
/// </remarks>
[StaFact]
public void RunSwitchesToMainThreadAndPosts()
{
var task = Task.Run(delegate
{
try
{
this.asyncPump.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
SynchronizationContext.Current.Post(s => { }, null);
});
}
finally
{
this.testFrame.Continue = false;
}
});
// Now let the request proceed through.
this.PushFrame();
task.Wait(); // rethrow exceptions.
}
/// <summary>
/// Checks that posting to the SynchronizationContext.Current doesn't cause a hang.
/// </summary>
[StaFact]
public void RunSwitchesToMainThreadAndPostsTwice()
{
((DerivedJoinableTaskFactory)this.asyncPump).AssumeConcurrentUse = true;
var task = Task.Run(delegate
{
try
{
this.asyncPump.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
SynchronizationContext.Current.Post(s => { }, null);
SynchronizationContext.Current.Post(s => { }, null);
});
}
finally
{
this.testFrame.Continue = false;
}
});
// Now let the request proceed through.
this.PushFrame();
task.Wait(); // rethrow exceptions.
}
/// <summary>
/// Checks that posting to the SynchronizationContext.Current doesn't cause a hang.
/// </summary>
[StaFact]
public void RunSwitchesToMainThreadAndPostsTwiceDoesNotImpactJoinableTaskCompletion()
{
((DerivedJoinableTaskFactory)this.asyncPump).AssumeConcurrentUse = true;
Task task = null;
task = Task.Run(delegate
{
try
{
this.asyncPump.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
// Kick off work that should *not* impact the completion of
// the JoinableTask that lives within this Run delegate.
// And enforce the assertion by blocking the main thread until
// the JoinableTask is done, which would deadlock if the
// JoinableTask were inappropriately blocking on the completion
// of the posted message.
SynchronizationContext.Current.Post(s => { task.Wait(); }, null);
// Post one more time, since an implementation detail may unblock
// the JoinableTask for the very last posted message for reasons that
// don't apply for other messages.
SynchronizationContext.Current.Post(s => { }, null);
});
}
finally
{
this.testFrame.Continue = false;
}
});
// Now let the request proceed through.
this.PushFrame();
task.Wait(); // rethrow exceptions.
}
[StaFact]
public void SwitchToMainThreadImmediatelyShouldNotHang()
{
((DerivedJoinableTaskFactory)this.asyncPump).AssumeConcurrentUse = true;
var task1Started = new AsyncManualResetEvent(false);
var task2Started = new AsyncManualResetEvent(false);
this.asyncPump.Run(async delegate
{
var child1Task = Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync().GetAwaiter().YieldAndNotify(task1Started);
});
var child2Task = Task.Run(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync().GetAwaiter().YieldAndNotify(task2Started);
});
task1Started.WaitAsync().Wait();
task2Started.WaitAsync().Wait();
await child1Task;
await child2Task;
});
}
[StaFact]
public void MultipleSwitchToMainThreadShouldNotHang()
{
((DerivedJoinableTaskFactory)this.asyncPump).AssumeConcurrentUse = true;
JoinableTask task1 = null, task2 = null;
var taskStarted = new AsyncManualResetEvent();
var testEnded = new AsyncManualResetEvent();
var dependentWork1Queued = new AsyncManualResetEvent();
var dependentWork2Queued = new AsyncManualResetEvent();
var dependentWork1Finished = new AsyncManualResetEvent();
var dependentWork2Finished = new AsyncManualResetEvent();
var separatedTask = Task.Run(async delegate
{
task1 = this.asyncPump.RunAsync(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync()
.GetAwaiter().YieldAndNotify(dependentWork1Queued);
dependentWork1Finished.Set();
});
task2 = this.asyncPump.RunAsync(async delegate
{
var collection = new JoinableTaskCollection(this.joinableCollection.Context);
collection.Add(task1);
collection.Join();
await this.asyncPump.SwitchToMainThreadAsync()
.GetAwaiter().YieldAndNotify(dependentWork2Queued);
dependentWork2Finished.Set();
await testEnded;
});
taskStarted.Set();
await testEnded;
});
this.asyncPump.Run(async delegate
{
await taskStarted;
await dependentWork1Queued;
await dependentWork2Queued;
var collection = new JoinableTaskCollection(this.joinableCollection.Context);
collection.Add(task2);
collection.Join();
await dependentWork1Finished;
await dependentWork2Finished;
testEnded.Set();
});
this.asyncPump.Run(async delegate
{
using (this.joinableCollection.Join())
{
await task1;
await task2;
await separatedTask;
}
});
}
[StaFact]
public void SwitchToMainThreadWithDelayedDependencyShouldNotHang()
{
JoinableTask task1 = null, task2 = null;
var taskStarted = new AsyncManualResetEvent();
var testEnded = new AsyncManualResetEvent();
var dependentWorkAllowed = new AsyncManualResetEvent();
var indirectDependencyAllowed = new AsyncManualResetEvent();
var dependentWorkQueued = new AsyncManualResetEvent();
var dependentWorkFinished = new AsyncManualResetEvent();
var separatedTask = Task.Run(async delegate
{
var taskCollection = new JoinableTaskCollection(this.context);
var factory = new JoinableTaskFactory(taskCollection);
task1 = this.asyncPump.RunAsync(async delegate
{
await dependentWorkAllowed;
await factory.SwitchToMainThreadAsync()
.GetAwaiter().YieldAndNotify(dependentWorkQueued);
dependentWorkFinished.Set();
});
task2 = this.asyncPump.RunAsync(async delegate
{
await indirectDependencyAllowed;
var collection = new JoinableTaskCollection(this.joinableCollection.Context);
collection.Add(task1);
await Task.Delay(AsyncDelay);
collection.Join();
await testEnded;
});
taskStarted.Set();
await testEnded;
});
this.asyncPump.Run(async delegate
{
await taskStarted;
dependentWorkAllowed.Set();
await dependentWorkQueued;
var collection = new JoinableTaskCollection(this.joinableCollection.Context);
collection.Add(task2);
collection.Join();
indirectDependencyAllowed.Set();
await dependentWorkFinished;
testEnded.Set();
});
this.asyncPump.Run(async delegate
{
using (this.joinableCollection.Join())
{
await task1;
await task2;
await separatedTask;
}
});
}
[StaFact]
public void DoubleJoinedTaskDisjoinCorrectly()
{
JoinableTask task1 = null;
var taskStarted = new AsyncManualResetEvent();
var dependentFirstWorkCompleted = new AsyncManualResetEvent();
var dependentSecondWorkAllowed = new AsyncManualResetEvent();
var mainThreadDependentSecondWorkQueued = new AsyncManualResetEvent();
var testEnded = new AsyncManualResetEvent();
var separatedTask = Task.Run(async delegate
{
task1 = this.asyncPump.RunAsync(async delegate
{
await this.asyncPump.SwitchToMainThreadAsync();
await TaskScheduler.Default;
dependentFirstWorkCompleted.Set();
await dependentSecondWorkAllowed;
await this.asyncPump.SwitchToMainThreadAsync()
.GetAwaiter().YieldAndNotify(mainThreadDependentSecondWorkQueued);
});
taskStarted.Set();
await testEnded;
});
this.asyncPump.Run(async delegate
{
await taskStarted;
var collection1 = new JoinableTaskCollection(this.joinableCollection.Context);
collection1.Add(task1);
var collection2 = new JoinableTaskCollection(this.joinableCollection.Context);
collection2.Add(task1);
using (collection1.Join())
{
using (collection2.Join())
{
}