66using System . Diagnostics . Tracing ;
77using System . Linq ;
88using System . Reflection ;
9+ using System . Threading ;
910using Microsoft . DotNet . RemoteExecutor ;
1011using Microsoft . DotNet . XUnitExtensions ;
1112using Xunit ;
@@ -21,6 +22,7 @@ public class RuntimeAsyncTests
2122 private static readonly FieldInfo s_continuationTimestampsField = GetCorLibClassStaticField ( "System.Threading.Tasks.Task" , "s_runtimeAsyncContinuationTimestamps" ) ;
2223 private static readonly FieldInfo s_activeTasksField = GetCorLibClassStaticField ( "System.Threading.Tasks.Task" , "s_currentActiveTasks" ) ;
2324 private static readonly FieldInfo s_activeFlagsField = GetCorLibClassStaticField ( "System.Runtime.CompilerServices.AsyncInstrumentation" , "s_activeFlags" ) ;
25+ private static readonly FieldInfo s_taskIdField = GetCorLibClassInstanceField ( "System.Threading.Tasks.Task" , "m_taskId" ) ;
2426
2527 private static readonly object s_debuggerLock = new object ( ) ;
2628
@@ -93,6 +95,23 @@ private static FieldInfo GetCorLibClassStaticField(string className, string fiel
9395 return field ;
9496 }
9597
98+ private static FieldInfo GetCorLibClassInstanceField ( string className , string fieldName )
99+ {
100+ Type ? classType = typeof ( object ) . Assembly . GetType ( className ) ;
101+ if ( classType == null )
102+ {
103+ throw new InvalidOperationException ( $ "Type '{ className } ' doesn't exist in System.Private.CoreLib.") ;
104+ }
105+
106+ FieldInfo ? field = classType . GetField ( fieldName , BindingFlags . Public | BindingFlags . NonPublic | BindingFlags . Instance ) ;
107+ if ( field == null )
108+ {
109+ throw new InvalidOperationException ( $ "Expected instance field '{ fieldName } ' to exist on type '{ className } '.") ;
110+ }
111+
112+ return field ;
113+ }
114+
96115 private static int GetTaskTimestampCount ( ) =>
97116 s_taskTimestampsField . GetValue ( null ) is Dictionary < int , long > dict ? dict . Count : 0 ;
98117
@@ -171,6 +190,12 @@ static async Task FuncThatWaitsTwice(TaskCompletionSource tcs1, TaskCompletionSo
171190 await tcs2 . Task ;
172191 }
173192
193+ [ System . Runtime . CompilerServices . RuntimeAsyncMethodGeneration ( true ) ]
194+ static async Task FuncThatWaitsOnce ( Task task )
195+ {
196+ await task ;
197+ }
198+
174199 [ System . Runtime . CompilerServices . RuntimeAsyncMethodGeneration ( true ) ]
175200 static async Task FuncThatInspectsContinuationTimestamps ( TaskCompletionSource tcs , Action callback )
176201 {
@@ -405,8 +430,8 @@ public void RuntimeAsync_TimestampsTrackedWhileInFlight()
405430 {
406431 AttachDebugger ( ) ;
407432
408- var tcs1 = new TaskCompletionSource ( ) ;
409- var tcs2 = new TaskCompletionSource ( ) ;
433+ var tcs1 = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
434+ var tcs2 = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
410435 Task inflight = FuncThatWaitsTwice ( tcs1 , tcs2 ) ;
411436
412437 // Task is suspended on tcs1 — should be in active tasks
@@ -575,6 +600,169 @@ public void RuntimeAsync_TplEvents()
575600 } ) . Dispose ( ) ;
576601 }
577602
603+ [ ConditionalFact ( typeof ( RuntimeAsyncTests ) , nameof ( IsRemoteExecutorAndRuntimeAsyncSupported ) ) ]
604+ public void RuntimeAsync_TaskWaitEvents ( )
605+ {
606+ RemoteExecutor . Invoke ( ( ) =>
607+ {
608+ const int TaskWaitBeginId = 10 ;
609+ const int TaskWaitEndId = 11 ;
610+
611+ AttachDebugger ( ) ;
612+
613+ var events = new ConcurrentQueue < EventWrittenEventArgs > ( ) ;
614+ using ( var listener = new TestEventListener ( "System.Threading.Tasks.TplEventSource" , EventLevel . Verbose ) )
615+ {
616+ listener . RunWithCallback ( events . Enqueue , ( ) =>
617+ {
618+ var tcs1 = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
619+ var tcs2 = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
620+ Task runtimeAsyncTask = FuncThatWaitsTwice ( tcs1 , tcs2 ) ;
621+ int runtimeAsyncTaskId = runtimeAsyncTask . Id ;
622+ int firstAwaitedTaskId = tcs1 . Task . Id ;
623+ int secondAwaitedTaskId = tcs2 . Task . Id ;
624+
625+ Assert . True (
626+ SpinWait . SpinUntil (
627+ ( ) => events . Any ( e =>
628+ e . EventId == TaskWaitBeginId &&
629+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
630+ ( int ) e . Payload [ 2 ] ! == firstAwaitedTaskId &&
631+ ( int ) e . Payload [ 4 ] ! == runtimeAsyncTaskId ) ,
632+ TimeSpan . FromSeconds ( 30 ) ) ,
633+ "Expected the RuntimeAsync task to suspend on the first task." ) ;
634+ Assert . DoesNotContain ( events , e =>
635+ e . EventId == TaskWaitEndId &&
636+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
637+ ( int ) e . Payload ! [ 2 ] ! == firstAwaitedTaskId ) ;
638+
639+ tcs1 . SetResult ( ) ;
640+
641+ Assert . True (
642+ SpinWait . SpinUntil (
643+ ( ) => events . Any ( e =>
644+ e . EventId == TaskWaitBeginId &&
645+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
646+ ( int ) e . Payload [ 2 ] ! == secondAwaitedTaskId ) ,
647+ TimeSpan . FromSeconds ( 30 ) ) ,
648+ "Expected the RuntimeAsync task to suspend on the second task." ) ;
649+ Assert . Contains ( events , e =>
650+ e . EventId == TaskWaitEndId &&
651+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
652+ ( int ) e . Payload [ 2 ] ! == firstAwaitedTaskId ) ;
653+ Assert . Contains ( events , e =>
654+ e . EventId == TaskWaitBeginId &&
655+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
656+ ( int ) e . Payload [ 2 ] ! == secondAwaitedTaskId &&
657+ ( int ) e . Payload [ 4 ] ! == runtimeAsyncTaskId ) ;
658+ Assert . DoesNotContain ( events , e =>
659+ e . EventId == TaskWaitEndId &&
660+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
661+ ( int ) e . Payload ! [ 2 ] ! == secondAwaitedTaskId ) ;
662+
663+ tcs2 . SetResult ( ) ;
664+ runtimeAsyncTask . GetAwaiter ( ) . GetResult ( ) ;
665+
666+ Assert . True (
667+ SpinWait . SpinUntil (
668+ ( ) => events . Any ( e =>
669+ e . EventId == TaskWaitEndId &&
670+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
671+ ( int ) e . Payload [ 2 ] ! == secondAwaitedTaskId ) ,
672+ TimeSpan . FromSeconds ( 30 ) ) ,
673+ "Expected the RuntimeAsync task to finish waiting on the second task." ) ;
674+ Assert . Contains ( events , e =>
675+ e . EventId == TaskWaitEndId &&
676+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
677+ ( int ) e . Payload [ 2 ] ! == secondAwaitedTaskId ) ;
678+ } ) ;
679+ }
680+
681+ DetachDebugger ( ) ;
682+ } ) . Dispose ( ) ;
683+ }
684+
685+ [ ConditionalFact ( typeof ( RuntimeAsyncTests ) , nameof ( IsRemoteExecutorAndRuntimeAsyncSupported ) ) ]
686+ public void RuntimeAsync_TaskWaitEndEventsForFaultedAndCanceledTasks ( )
687+ {
688+ RemoteExecutor . Invoke ( ( ) =>
689+ {
690+ const int TaskWaitBeginId = 10 ;
691+ const int TaskWaitEndId = 11 ;
692+
693+ AttachDebugger ( ) ;
694+
695+ var events = new ConcurrentQueue < EventWrittenEventArgs > ( ) ;
696+ using ( var listener = new TestEventListener ( "System.Threading.Tasks.TplEventSource" , EventLevel . Verbose ) )
697+ {
698+ listener . RunWithCallback ( events . Enqueue , ( ) =>
699+ {
700+ foreach ( bool cancel in new [ ] { false , true } )
701+ {
702+ var tcs = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
703+ Task runtimeAsyncTask = FuncThatWaitsOnce ( tcs . Task ) ;
704+ int runtimeAsyncTaskId = runtimeAsyncTask . Id ;
705+ int awaitedTaskId = tcs . Task . Id ;
706+
707+ Assert . True (
708+ SpinWait . SpinUntil (
709+ ( ) => events . Any ( e =>
710+ e . EventId == TaskWaitBeginId &&
711+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
712+ ( int ) e . Payload [ 2 ] ! == awaitedTaskId ) ,
713+ TimeSpan . FromSeconds ( 30 ) ) ,
714+ $ "Expected a wait-begin event for the { ( cancel ? "canceled" : "faulted" ) } task.") ;
715+
716+ if ( cancel )
717+ {
718+ tcs . SetCanceled ( ) ;
719+ Assert . ThrowsAny < OperationCanceledException > ( ( ) => runtimeAsyncTask . GetAwaiter ( ) . GetResult ( ) ) ;
720+ }
721+ else
722+ {
723+ tcs . SetException ( new InvalidOperationException ( ) ) ;
724+ Assert . Throws < InvalidOperationException > ( ( ) => runtimeAsyncTask . GetAwaiter ( ) . GetResult ( ) ) ;
725+ }
726+
727+ Assert . True (
728+ SpinWait . SpinUntil (
729+ ( ) => events . Any ( e =>
730+ e . EventId == TaskWaitEndId &&
731+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
732+ ( int ) e . Payload [ 2 ] ! == awaitedTaskId ) ,
733+ TimeSpan . FromSeconds ( 30 ) ) ,
734+ $ "Expected a wait-end event for the { ( cancel ? "canceled" : "faulted" ) } task.") ;
735+ }
736+ } ) ;
737+ }
738+
739+ DetachDebugger ( ) ;
740+ } ) . Dispose ( ) ;
741+ }
742+
743+ [ ConditionalFact ( typeof ( RuntimeAsyncTests ) , nameof ( IsRemoteExecutorAndRuntimeAsyncSupported ) ) ]
744+ public void RuntimeAsync_TaskWaitEventsArePayForPlay ( )
745+ {
746+ RemoteExecutor . Invoke ( ( ) =>
747+ {
748+ AttachDebugger ( ) ;
749+
750+ var tcs1 = new TaskCompletionSource ( ) ;
751+ var tcs2 = new TaskCompletionSource ( ) ;
752+ Task runtimeAsyncTask = FuncThatWaitsTwice ( tcs1 , tcs2 ) ;
753+
754+ Assert . Equal ( 0 , ( int ) s_taskIdField . GetValue ( tcs1 . Task ) ! ) ;
755+
756+ tcs1 . SetResult ( ) ;
757+ Assert . Equal ( 0 , ( int ) s_taskIdField . GetValue ( tcs2 . Task ) ! ) ;
758+
759+ tcs2 . SetResult ( ) ;
760+ runtimeAsyncTask . GetAwaiter ( ) . GetResult ( ) ;
761+
762+ DetachDebugger ( ) ;
763+ } ) . Dispose ( ) ;
764+ }
765+
578766 [ ConditionalFact ( typeof ( RuntimeAsyncTests ) , nameof ( IsRemoteExecutorAndRuntimeAsyncSupported ) ) ]
579767 public void RuntimeAsync_SuspensionTimestampsAreDistinct ( )
580768 {
@@ -601,13 +789,18 @@ public void RuntimeAsync_NoTplEventsWithoutDebugger()
601789 {
602790 RemoteExecutor . Invoke ( ( ) =>
603791 {
792+ const int TaskWaitBeginId = 10 ;
793+ const int TaskWaitEndId = 11 ;
604794 const int TraceOperationBeginId = 14 ;
605795 const string RuntimeAsyncTaskOperationName = "System.Runtime.CompilerServices.AsyncHelpers+RuntimeAsyncTask" ;
606796
607797 // Enable TplEventSource WITHOUT setting s_asyncDebuggingEnabled.
608798 // The AsyncDebugger guard should prevent the V2 async instrumentation
609799 // from emitting any TPL causality events.
610800 var events = new ConcurrentQueue < EventWrittenEventArgs > ( ) ;
801+ int runtimeAsyncTaskId = 0 ;
802+ int firstAwaitedTaskId = 0 ;
803+ int secondAwaitedTaskId = 0 ;
611804 using ( var listener = new TestEventListener ( "System.Threading.Tasks.TplEventSource" , EventLevel . Verbose ) )
612805 {
613806 listener . RunWithCallback ( events . Enqueue , ( ) =>
@@ -616,9 +809,28 @@ public void RuntimeAsync_NoTplEventsWithoutDebugger()
616809 {
617810 Func ( ) . GetAwaiter ( ) . GetResult ( ) ;
618811 }
812+
813+ var tcs1 = new TaskCompletionSource ( ) ;
814+ var tcs2 = new TaskCompletionSource ( ) ;
815+ Task runtimeAsyncTask = FuncThatWaitsTwice ( tcs1 , tcs2 ) ;
816+ runtimeAsyncTaskId = runtimeAsyncTask . Id ;
817+ firstAwaitedTaskId = tcs1 . Task . Id ;
818+ secondAwaitedTaskId = tcs2 . Task . Id ;
819+ tcs1 . SetResult ( ) ;
820+ tcs2 . SetResult ( ) ;
821+ runtimeAsyncTask . GetAwaiter ( ) . GetResult ( ) ;
619822 } ) ;
620823 }
621824
825+ Assert . DoesNotContain ( events , e =>
826+ e . EventId == TaskWaitBeginId &&
827+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
828+ ( ( int ) e . Payload [ 2 ] ! == firstAwaitedTaskId || ( int ) e . Payload [ 2 ] ! == secondAwaitedTaskId ) ) ;
829+ Assert . DoesNotContain ( events , e =>
830+ e . EventId == TaskWaitEndId &&
831+ ( int ) e . Payload ! [ 1 ] ! == runtimeAsyncTaskId &&
832+ ( ( int ) e . Payload [ 2 ] ! == firstAwaitedTaskId || ( int ) e . Payload [ 2 ] ! == secondAwaitedTaskId ) ) ;
833+
622834 // TraceOperationBegin with the RuntimeAsyncTask operation name is uniquely
623835 // emitted by V2 async instrumentation. It must not appear without a debugger.
624836 Assert . DoesNotContain ( events , e =>
0 commit comments