summaryrefslogtreecommitdiff
path: root/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs
blob: e7a7060e4962b38b887fc64ebffcc77210f09ec0 (plain)
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
// 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.

// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Implementation of task continuations, TaskContinuation, and its descendants.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

using System.Security;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
using System.Threading;

#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
#endif // FEATURE_COMINTEROP

namespace System.Threading.Tasks
{
    // Task type used to implement: Task ContinueWith(Action<Task,...>)
    internal sealed class ContinuationTaskFromTask : Task
    {
        private Task m_antecedent;

        public ContinuationTaskFromTask(
            Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
            base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
        {
            Debug.Assert(action is Action<Task> || action is Action<Task, object>,
                "Invalid delegate type in ContinuationTaskFromTask");
            m_antecedent = antecedent;
        }

        /// <summary>
        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
        /// </summary>        
        internal override void InnerInvoke()
        {
            // Get and null out the antecedent.  This is crucial to avoid a memory
            // leak with long chains of continuations.
            var antecedent = m_antecedent;
            Debug.Assert(antecedent != null,
                "No antecedent was set for the ContinuationTaskFromTask.");
            m_antecedent = null;

            // Notify the debugger we're completing an asynchronous wait on a task
            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();

            // Invoke the delegate
            Debug.Assert(m_action != null);
            if (m_action is Action<Task> action)
            {
                action(antecedent);
                return;
            }

            if (m_action is Action<Task, object> actionWithState)
            {
                actionWithState(antecedent, m_stateObject);
                return;
            }
            Debug.Fail("Invalid m_action in ContinuationTaskFromTask");
        }
    }

    // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>)
    internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult>
    {
        private Task m_antecedent;

        public ContinuationResultTaskFromTask(
            Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
            base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
        {
            Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
                "Invalid delegate type in ContinuationResultTaskFromTask");
            m_antecedent = antecedent;
        }

        /// <summary>
        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
        /// </summary>        
        internal override void InnerInvoke()
        {
            // Get and null out the antecedent.  This is crucial to avoid a memory
            // leak with long chains of continuations.
            var antecedent = m_antecedent;
            Debug.Assert(antecedent != null,
                "No antecedent was set for the ContinuationResultTaskFromTask.");
            m_antecedent = null;

            // Notify the debugger we're completing an asynchronous wait on a task
            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();

            // Invoke the delegate
            Debug.Assert(m_action != null);
            if (m_action is Func<Task, TResult> func)
            {
                m_result = func(antecedent);
                return;
            }

            if (m_action is Func<Task, object, TResult> funcWithState)
            {
                m_result = funcWithState(antecedent, m_stateObject);
                return;
            }
            Debug.Fail("Invalid m_action in ContinuationResultTaskFromTask");
        }
    }

    // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>)
    internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task
    {
        private Task<TAntecedentResult> m_antecedent;

        public ContinuationTaskFromResultTask(
            Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
            base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
        {
            Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
                "Invalid delegate type in ContinuationTaskFromResultTask");
            m_antecedent = antecedent;
        }

        /// <summary>
        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
        /// </summary>
        internal override void InnerInvoke()
        {
            // Get and null out the antecedent.  This is crucial to avoid a memory
            // leak with long chains of continuations.
            var antecedent = m_antecedent;
            Debug.Assert(antecedent != null,
                "No antecedent was set for the ContinuationTaskFromResultTask.");
            m_antecedent = null;

            // Notify the debugger we're completing an asynchronous wait on a task
            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();

            // Invoke the delegate
            Debug.Assert(m_action != null);
            if (m_action is Action<Task<TAntecedentResult>> action)
            {
                action(antecedent);
                return;
            }

            if (m_action is Action<Task<TAntecedentResult>, object> actionWithState)
            {
                actionWithState(antecedent, m_stateObject);
                return;
            }
            Debug.Fail("Invalid m_action in ContinuationTaskFromResultTask");
        }
    }

    // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>)
    internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult>
    {
        private Task<TAntecedentResult> m_antecedent;

        public ContinuationResultTaskFromResultTask(
            Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
            base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
        {
            Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
                "Invalid delegate type in ContinuationResultTaskFromResultTask");
            m_antecedent = antecedent;
        }

        /// <summary>
        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
        /// </summary>
        internal override void InnerInvoke()
        {
            // Get and null out the antecedent.  This is crucial to avoid a memory
            // leak with long chains of continuations.
            var antecedent = m_antecedent;
            Debug.Assert(antecedent != null,
                "No antecedent was set for the ContinuationResultTaskFromResultTask.");
            m_antecedent = null;

            // Notify the debugger we're completing an asynchronous wait on a task
            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();

            // Invoke the delegate
            Debug.Assert(m_action != null);
            if (m_action is Func<Task<TAntecedentResult>, TResult> func)
            {
                m_result = func(antecedent);
                return;
            }

            if (m_action is Func<Task<TAntecedentResult>, object, TResult> funcWithState)
            {
                m_result = funcWithState(antecedent, m_stateObject);
                return;
            }
            Debug.Fail("Invalid m_action in ContinuationResultTaskFromResultTask");
        }
    }

    // For performance reasons, we don't just have a single way of representing
    // a continuation object.  Rather, we have a hierarchy of types:
    // - TaskContinuation: abstract base that provides a virtual Run method
    //     - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration
    //     - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default
    //         - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler
    //         - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx

    /// <summary>Represents a continuation.</summary>
    internal abstract class TaskContinuation
    {
        /// <summary>Inlines or schedules the continuation.</summary>
        /// <param name="completedTask">The antecedent task that has completed.</param>
        /// <param name="bCanInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
        internal abstract void Run(Task completedTask, bool bCanInlineContinuationTask);

        /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary>
        /// <param name="task">The task to run</param>
        /// <param name="needsProtection">
        /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false.
        /// </param>
        protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
        {
            Debug.Assert(task != null);
            Debug.Assert(task.m_taskScheduler != null);

            // Set the TASK_STATE_STARTED flag.  This only needs to be done
            // if the task may be canceled or if someone else has a reference to it
            // that may try to execute it.
            if (needsProtection)
            {
                if (!task.MarkStarted())
                    return; // task has been previously started or canceled.  Stop processing.
            }
            else
            {
                task.m_stateFlags |= Task.TASK_STATE_STARTED;
            }

            // Try to inline it but queue if we can't
            try
            {
                if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false))
                {
                    task.m_taskScheduler.InternalQueueTask(task);
                }
            }
            catch (Exception e)
            {
                // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted.
                // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, 
                // because it would already have been handled in Task.Execute()
                if (!(e is ThreadAbortException &&
                      (task.m_stateFlags & Task.TASK_STATE_THREAD_WAS_ABORTED) != 0))    // this ensures TAEs from QueueTask will be wrapped in TSE
                {
                    TaskSchedulerException tse = new TaskSchedulerException(e);
                    task.AddException(tse);
                    task.Finish(false);
                }

                // Don't re-throw.
            }
        }

        internal abstract Delegate[] GetDelegateContinuationsForDebugger();
    }

    /// <summary>Provides the standard implementation of a task continuation.</summary>
    internal class StandardTaskContinuation : TaskContinuation
    {
        /// <summary>The unstarted continuation task.</summary>
        internal readonly Task m_task;
        /// <summary>The options to use with the continuation task.</summary>
        internal readonly TaskContinuationOptions m_options;
        /// <summary>The task scheduler with which to run the continuation task.</summary>
        private readonly TaskScheduler m_taskScheduler;

        /// <summary>Initializes a new continuation.</summary>
        /// <param name="task">The task to be activated.</param>
        /// <param name="options">The continuation options.</param>
        /// <param name="scheduler">The scheduler to use for the continuation.</param>
        internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler)
        {
            Debug.Assert(task != null, "TaskContinuation ctor: task is null");
            Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null");
            m_task = task;
            m_options = options;
            m_taskScheduler = scheduler;
            if (AsyncCausalityTracer.LoggingOn)
                AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + task.m_action.Method.Name, 0);

            if (Task.s_asyncDebuggingEnabled)
            {
                Task.AddToActiveTasks(m_task);
            }
        }

        /// <summary>Invokes the continuation for the target completion task.</summary>
        /// <param name="completedTask">The completed task.</param>
        /// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
        internal override void Run(Task completedTask, bool bCanInlineContinuationTask)
        {
            Debug.Assert(completedTask != null);
            Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");

            // Check if the completion status of the task works with the desired 
            // activation criteria of the TaskContinuationOptions.
            TaskContinuationOptions options = m_options;
            bool isRightKind =
                completedTask.IsCompletedSuccessfully ?
                    (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 :
                    (completedTask.IsCanceled ?
                        (options & TaskContinuationOptions.NotOnCanceled) == 0 :
                        (options & TaskContinuationOptions.NotOnFaulted) == 0);

            // If the completion status is allowed, run the continuation.
            Task continuationTask = m_task;
            if (isRightKind)
            {
                //If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token)
                //we will still flow it to ScheduleAndStart() were it will check the status before running
                //We check here to avoid faulty logs that contain a join event to an operation that was already set as completed.
                if (!continuationTask.IsCanceled && AsyncCausalityTracer.LoggingOn)
                {
                    // Log now that we are sure that this continuation is being ran
                    AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, continuationTask.Id, CausalityRelation.AssignDelegate);
                }
                continuationTask.m_taskScheduler = m_taskScheduler;

                // Either run directly or just queue it up for execution, depending
                // on whether synchronous or asynchronous execution is wanted.
                if (bCanInlineContinuationTask && // inlining is allowed by the caller
                    (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator
                {
                    InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true);
                }
                else
                {
                    try { continuationTask.ScheduleAndStart(needsProtection: true); }
                    catch (TaskSchedulerException)
                    {
                        // No further action is necessary -- ScheduleAndStart() already transitioned the 
                        // task to faulted.  But we want to make sure that no exception is thrown from here.
                    }
                }
            }
            // Otherwise, the final state of this task does not match the desired
            // continuation activation criteria; cancel it to denote this.
            else continuationTask.InternalCancel(false);
        }

        internal override Delegate[] GetDelegateContinuationsForDebugger()
        {
            if (m_task.m_action == null)
            {
                return m_task.GetDelegateContinuationsForDebugger();
            }

            return new Delegate[] { m_task.m_action };
        }
    }

    /// <summary>Task continuation for awaiting with a current synchronization context.</summary>
    internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation
    {
        /// <summary>SendOrPostCallback delegate to invoke the action.</summary>
        private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical
        /// <summary>Cached delegate for PostAction</summary>
        private static ContextCallback s_postActionCallback;
        /// <summary>The context with which to run the action.</summary>
        private readonly SynchronizationContext m_syncContext;

        /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary>
        /// <param name="context">The synchronization context with which to invoke the action.  Must not be null.</param>
        /// <param name="action">The action to invoke. Must not be null.</param>
        /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
        internal SynchronizationContextAwaitTaskContinuation(
            SynchronizationContext context, Action action, bool flowExecutionContext) :
            base(action, flowExecutionContext)
        {
            Debug.Assert(context != null);
            m_syncContext = context;
        }

        /// <summary>Inlines or schedules the continuation.</summary>
        /// <param name="task">The antecedent task, which is ignored.</param>
        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
        internal sealed override void Run(Task task, bool canInlineContinuationTask)
        {
            // If we're allowed to inline, run the action on this thread.
            if (canInlineContinuationTask &&
                m_syncContext == SynchronizationContext.Current)
            {
                RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask);
            }
            // Otherwise, Post the action back to the SynchronizationContext.
            else
            {
                TplEtwProvider etwLog = TplEtwProvider.Log;
                if (etwLog.IsEnabled())
                {
                    m_continuationId = Task.NewId();
                    etwLog.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId);
                }
                RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask);
            }
            // Any exceptions will be handled by RunCallback.
        }

        /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary>
        /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param>
        private static void PostAction(object state)
        {
            var c = (SynchronizationContextAwaitTaskContinuation)state;

            TplEtwProvider etwLog = TplEtwProvider.Log;
            if (etwLog.TasksSetActivityIds && c.m_continuationId != 0)
            {
                c.m_syncContext.Post(s_postCallback, GetActionLogDelegate(c.m_continuationId, c.m_action));
            }
            else
            {
                c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method
            }
        }

        private static Action GetActionLogDelegate(int continuationId, Action action)
        {
            return () =>
                {
                    Guid savedActivityId;
                    Guid activityId = TplEtwProvider.CreateGuidForTaskID(continuationId);
                    System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId);
                    try { action(); }
                    finally { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); }
                };
        }

        /// <summary>Gets a cached delegate for the PostAction method.</summary>
        /// <returns>
        /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation 
        /// to be passed as state.
        /// </returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static ContextCallback GetPostActionCallback()
        {
            ContextCallback callback = s_postActionCallback;
            if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate
            return callback;
        }
    }

    /// <summary>Task continuation for awaiting with a task scheduler.</summary>
    internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation
    {
        /// <summary>The scheduler on which to run the action.</summary>
        private readonly TaskScheduler m_scheduler;

        /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary>
        /// <param name="scheduler">The task scheduler with which to invoke the action.  Must not be null.</param>
        /// <param name="action">The action to invoke. Must not be null.</param>
        /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
        internal TaskSchedulerAwaitTaskContinuation(
            TaskScheduler scheduler, Action action, bool flowExecutionContext) :
            base(action, flowExecutionContext)
        {
            Debug.Assert(scheduler != null);
            m_scheduler = scheduler;
        }

        /// <summary>Inlines or schedules the continuation.</summary>
        /// <param name="ignored">The antecedent task, which is ignored.</param>
        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
        internal sealed override void Run(Task ignored, bool canInlineContinuationTask)
        {
            // If we're targeting the default scheduler, we can use the faster path provided by the base class.
            if (m_scheduler == TaskScheduler.Default)
            {
                base.Run(ignored, canInlineContinuationTask);
            }
            else
            {
                // We permit inlining if the caller allows us to, and 
                // either we're on a thread pool thread (in which case we're fine running arbitrary code)
                // or we're already on the target scheduler (in which case we'll just ask the scheduler
                // whether it's ok to run here).  We include the IsThreadPoolThread check here, whereas
                // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed
                // to in AwaitTaskContinuation.Run where it restricts what's allowed.
                bool inlineIfPossible = canInlineContinuationTask &&
                    (TaskScheduler.InternalCurrent == m_scheduler || Thread.CurrentThread.IsThreadPoolThread);

                // Create the continuation task task. If we're allowed to inline, try to do so.  
                // The target scheduler may still deny us from executing on this thread, in which case this'll be queued.
                var task = CreateTask(state =>
                {
                    try { ((Action)state)(); }
                    catch (Exception exc) { ThrowAsyncIfNecessary(exc); }
                }, m_action, m_scheduler);

                if (inlineIfPossible)
                {
                    InlineIfPossibleOrElseQueue(task, needsProtection: false);
                }
                else
                {
                    // We need to run asynchronously, so just schedule the task.
                    try { task.ScheduleAndStart(needsProtection: false); }
                    catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted
                }
            }
        }
    }

    /// <summary>Base task continuation class used for await continuations.</summary>
    internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem
    {
        /// <summary>The ExecutionContext with which to run the continuation.</summary>
        private readonly ExecutionContext m_capturedContext;
        /// <summary>The action to invoke.</summary>
        protected readonly Action m_action;

        protected int m_continuationId;

        /// <summary>Initializes the continuation.</summary>
        /// <param name="action">The action to invoke. Must not be null.</param>
        /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
        internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
        {
            Debug.Assert(action != null);
            m_action = action;
            if (flowExecutionContext)
            {
                m_capturedContext = ExecutionContext.Capture();
            }
        }

        /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary>
        /// <param name="action">The action to run. Must not be null.</param>
        /// <param name="state">The state to pass to the action. Must not be null.</param>
        /// <param name="scheduler">The scheduler to target.</param>
        /// <returns>The created task.</returns>
        protected Task CreateTask(Action<object> action, object state, TaskScheduler scheduler)
        {
            Debug.Assert(action != null);
            Debug.Assert(scheduler != null);

            return new Task(
                action, state, null, default,
                TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler)
            {
                CapturedContext = m_capturedContext
            };
        }

        /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary>
        /// <param name="task">The antecedent task, which is ignored.</param>
        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
        internal override void Run(Task task, bool canInlineContinuationTask)
        {
            // For the base AwaitTaskContinuation, we allow inlining if our caller allows it
            // and if we're in a "valid location" for it.  See the comments on 
            // IsValidLocationForInlining for more about what's valid.  For performance
            // reasons we would like to always inline, but we don't in some cases to avoid
            // running arbitrary amounts of work in suspected "bad locations", like UI threads.
            if (canInlineContinuationTask && IsValidLocationForInlining)
            {
                RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction
            }
            else
            {
                TplEtwProvider etwLog = TplEtwProvider.Log;
                if (etwLog.IsEnabled())
                {
                    m_continuationId = Task.NewId();
                    etwLog.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId);
                }

                // We couldn't inline, so now we need to schedule it
                ThreadPool.UnsafeQueueUserWorkItemInternal(this, preferLocal: true);
            }
        }

        /// <summary>
        /// Gets whether the current thread is an appropriate location to inline a continuation's execution.
        /// </summary>
        /// <remarks>
        /// Returns whether SynchronizationContext is null and we're in the default scheduler.
        /// If the await had a SynchronizationContext/TaskScheduler where it began and the 
        /// default/ConfigureAwait(true) was used, then we won't be on this path.  If, however, 
        /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were 
        /// naturally null/Default, then we might end up here.  If we do, we need to make sure
        /// that we don't execute continuations in a place that isn't set up to handle them, e.g.
        /// running arbitrary amounts of code on the UI thread.  It would be "correct", but very
        /// expensive, to always run the continuations asynchronously, incurring lots of context
        /// switches and allocations and locks and the like.  As such, we employ the heuristic
        /// that if the current thread has a non-null SynchronizationContext or a non-default
        /// scheduler, then we better not run arbitrary continuations here.
        /// </remarks>
        internal static bool IsValidLocationForInlining
        {
            get
            {
                // If there's a SynchronizationContext, we'll be conservative and say 
                // this is a bad location to inline.
                var ctx = SynchronizationContext.Current;
                if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false;

                // Similarly, if there's a non-default TaskScheduler, we'll be conservative
                // and say this is a bad location to inline.
                var sched = TaskScheduler.InternalCurrent;
                return sched == null || sched == TaskScheduler.Default;
            }
        }

        void IThreadPoolWorkItem.Execute()
        {
            var etwLog = TplEtwProvider.Log;
            ExecutionContext context = m_capturedContext;

            if (!etwLog.IsEnabled() && context == null)
            {
                m_action();
                return;
            }

            Guid savedActivityId = Guid.Empty;
            if (etwLog.TasksSetActivityIds && m_continuationId != 0)
            {
                Guid activityId = TplEtwProvider.CreateGuidForTaskID(m_continuationId);
                System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId);
            }
            try
            {
                // We're not inside of a task, so t_currentTask doesn't need to be specially maintained.
                // We're on a thread pool thread with no higher-level callers, so exceptions can just propagate.

                ExecutionContext.CheckThreadPoolAndContextsAreDefault();
                // If there's no execution context or Default, just invoke the delegate as ThreadPool is on Default context.
                // We don't have to use ExecutionContext.Run for the Default context here as there is no extra processing after the delegate
                if (context == null || context.IsDefault)
                {
                    m_action();
                }
                // If there is an execution context, get the cached delegate and run the action under the context.
                else
                {
                    ExecutionContext.RunForThreadPoolUnsafe(context, s_invokeAction, m_action);
                }

                // ThreadPoolWorkQueue.Dispatch handles notifications and reset context back to default
            }
            finally
            {
                if (etwLog.TasksSetActivityIds && m_continuationId != 0)
                {
                    System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId);
                }
            }
        }

        /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary>
        private readonly static ContextCallback s_invokeContextCallback = (state) => ((Action)state)();
        private readonly static Action<Action> s_invokeAction = (action) => action();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        protected static ContextCallback GetInvokeActionCallback() => s_invokeContextCallback;

        /// <summary>Runs the callback synchronously with the provided state.</summary>
        /// <param name="callback">The callback to run.</param>
        /// <param name="state">The state to pass to the callback.</param>
        /// <param name="currentTask">A reference to Task.t_currentTask.</param>
        protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
        {
            Debug.Assert(callback != null);
            Debug.Assert(currentTask == Task.t_currentTask);

            // Pretend there's no current task, so that no task is seen as a parent
            // and TaskScheduler.Current does not reflect false information
            var prevCurrentTask = currentTask;
            try
            {
                if (prevCurrentTask != null) currentTask = null;

                ExecutionContext context = m_capturedContext;
                if (context == null)
                {
                    // If there's no captured context, just run the callback directly.
                    callback(state);
                }
                else
                {
                    // Otherwise, use the captured context to do so.
                    ExecutionContext.RunInternal(context, callback, state);
                }
            }
            catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs
            {
                ThrowAsyncIfNecessary(exc);
            }
            finally
            {
                // Restore the current task information
                if (prevCurrentTask != null) currentTask = prevCurrentTask;
            }
        }

        /// <summary>Invokes or schedules the action to be executed.</summary>
        /// <param name="action">The action to invoke or queue.</param>
        /// <param name="allowInlining">
        /// true to allow inlining, or false to force the action to run asynchronously.
        /// </param>
        /// <remarks>
        /// No ExecutionContext work is performed used.  This method is only used in the
        /// case where a raw Action continuation delegate was stored into the Task, which
        /// only happens in Task.SetContinuationForAwait if execution context flow was disabled
        /// via using TaskAwaiter.UnsafeOnCompleted or a similar path.
        /// </remarks>
        internal static void RunOrScheduleAction(Action action, bool allowInlining)
        {
            ref Task currentTask = ref Task.t_currentTask;
            Task prevCurrentTask = currentTask;

            // If we're not allowed to run here, schedule the action
            if (!allowInlining || !IsValidLocationForInlining)
            {
                UnsafeScheduleAction(action, prevCurrentTask);
                return;
            }

            // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution
            try
            {
                if (prevCurrentTask != null) currentTask = null;
                action();
            }
            catch (Exception exception)
            {
                ThrowAsyncIfNecessary(exception);
            }
            finally
            {
                if (prevCurrentTask != null) currentTask = prevCurrentTask;
            }
        }

        /// <summary>Invokes or schedules the action to be executed.</summary>
        /// <param name="box">The <see cref="IAsyncStateMachineBox"/> that needs to be invoked or queued.</param>
        /// <param name="allowInlining">
        /// true to allow inlining, or false to force the box's action to run asynchronously.
        /// </param>
        internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowInlining)
        {
            // Same logic as in the RunOrScheduleAction(Action, ...) overload, except invoking
            // box.Invoke instead of action().

            ref Task currentTask = ref Task.t_currentTask;
            Task prevCurrentTask = currentTask;

            // If we're not allowed to run here, schedule the action
            if (!allowInlining || !IsValidLocationForInlining)
            {
                // If logging is disabled, we can simply queue the box itself as a custom work
                // item, and its work item execution will just invoke its MoveNext.  However, if
                // logging is enabled, there is pre/post-work we need to do around logging to
                // match what's done for other continuations, and that requires flowing additional
                // information into the continuation, which we don't want to burden other cases of the
                // box with... so, in that case we just delegate to the AwaitTaskContinuation-based
                // path that already handles this, albeit at the expense of allocating the ATC
                // object, and potentially forcing the box's delegate into existence, when logging
                // is enabled.
                if (TplEtwProvider.Log.IsEnabled())
                {
                    UnsafeScheduleAction(box.MoveNextAction, prevCurrentTask);
                }
                else
                {
                    ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: true);
                }
                return;
            }

            // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution
            try
            {
                if (prevCurrentTask != null) currentTask = null;
                box.MoveNext();
            }
            catch (Exception exception)
            {
                ThrowAsyncIfNecessary(exception);
            }
            finally
            {
                if (prevCurrentTask != null) currentTask = prevCurrentTask;
            }
        }

        /// <summary>Schedules the action to be executed.  No ExecutionContext work is performed used.</summary>
        /// <param name="action">The action to invoke or queue.</param>
        /// <param name="task">The task scheduling the action.</param>
        internal static void UnsafeScheduleAction(Action action, Task task)
        {
            AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false);

            var etwLog = TplEtwProvider.Log;
            if (etwLog.IsEnabled() && task != null)
            {
                atc.m_continuationId = Task.NewId();
                etwLog.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, atc.m_continuationId);
            }

            ThreadPool.UnsafeQueueUserWorkItemInternal(atc, preferLocal: true);
        }

        /// <summary>Throws the exception asynchronously on the ThreadPool.</summary>
        /// <param name="exc">The exception to throw.</param>
        protected static void ThrowAsyncIfNecessary(Exception exc)
        {
            // Awaits should never experience an exception (other than an TAE or ADUE), 
            // unless a malicious user is explicitly passing a throwing action into the TaskAwaiter. 
            // We don't want to allow the exception to propagate on this stack, as it'll emerge in random places, 
            // and we can't fail fast, as that would allow for elevation of privilege.
            //
            // If unhandled error reporting APIs are available use those, otherwise since this 
            // would have executed on the thread pool otherwise, let it propagate there.

            if (!(exc is ThreadAbortException))
            {
#if FEATURE_COMINTEROP
                if (!WindowsRuntimeMarshal.ReportUnhandledError(exc))
#endif // FEATURE_COMINTEROP
                {
                    var edi = ExceptionDispatchInfo.Capture(exc);
                    ThreadPool.QueueUserWorkItem(s => ((ExceptionDispatchInfo)s).Throw(), edi);
                }
            }
        }

        internal override Delegate[] GetDelegateContinuationsForDebugger()
        {
            Debug.Assert(m_action != null);
            return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
        }
    }
}