/
Task.cs
6801 lines (6104 loc) · 341 KB
/
Task.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// A schedulable unit of work.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
namespace System.Threading.Tasks
{
/// <summary>
/// Represents the current stage in the lifecycle of a <see cref="Task"/>.
/// </summary>
public enum TaskStatus
{
/// <summary>
/// The task has been initialized but has not yet been scheduled.
/// </summary>
Created,
/// <summary>
/// The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.
/// </summary>
WaitingForActivation,
/// <summary>
/// The task has been scheduled for execution but has not yet begun executing.
/// </summary>
WaitingToRun,
/// <summary>
/// The task is running but has not yet completed.
/// </summary>
Running,
// /// <summary>
// /// The task is currently blocked in a wait state.
// /// </summary>
// Blocked,
/// <summary>
/// The task has finished executing and is implicitly waiting for
/// attached child tasks to complete.
/// </summary>
WaitingForChildrenToComplete,
/// <summary>
/// The task completed execution successfully.
/// </summary>
RanToCompletion,
/// <summary>
/// The task acknowledged cancellation by throwing an OperationCanceledException with its own CancellationToken
/// while the token was in signaled state, or the task's CancellationToken was already signaled before the
/// task started executing.
/// </summary>
Canceled,
/// <summary>
/// The task completed due to an unhandled exception.
/// </summary>
Faulted
}
/// <summary>
/// Represents an asynchronous operation.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="Task"/> instances may be created in a variety of ways. The most common approach is by
/// using the Task type's <see cref="Factory"/> property to retrieve a <see
/// cref="System.Threading.Tasks.TaskFactory"/> instance that can be used to create tasks for several
/// purposes. For example, to create a <see cref="Task"/> that runs an action, the factory's StartNew
/// method may be used:
/// <code>
/// // C#
/// var t = Task.Factory.StartNew(() => DoAction());
///
/// ' Visual Basic
/// Dim t = Task.Factory.StartNew(Function() DoAction())
/// </code>
/// </para>
/// <para>
/// The <see cref="Task"/> class also provides constructors that initialize the Task but that do not
/// schedule it for execution. For performance reasons, TaskFactory's StartNew method should be the
/// preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation
/// and scheduling must be separated, the constructors may be used, and the task's <see cref="Start()"/>
/// method may then be used to schedule the task for execution at a later time.
/// </para>
/// <para>
/// All members of <see cref="Task"/>, except for <see cref="Dispose()"/>, are thread-safe
/// and may be used from multiple threads concurrently.
/// </para>
/// <para>
/// For operations that return values, the <see cref="System.Threading.Tasks.Task{TResult}"/> class
/// should be used.
/// </para>
/// <para>
/// For developers implementing custom debuggers, several internal and private members of Task may be
/// useful (these may change from release to release). The Int32 m_taskId field serves as the backing
/// store for the <see cref="Id"/> property, however accessing this field directly from a debugger may be
/// more efficient than accessing the same value through the property's getter method (the
/// s_taskIdCounter Int32 counter is used to retrieve the next available ID for a Task). Similarly, the
/// Int32 m_stateFlags field stores information about the current lifecycle stage of the Task,
/// information also accessible through the <see cref="Status"/> property. The m_action System.Object
/// field stores a reference to the Task's delegate, and the m_stateObject System.Object field stores the
/// async state passed to the Task by the developer. Finally, for debuggers that parse stack frames, the
/// InternalWait method serves a potential marker for when a Task is entering a wait operation.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))]
[DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
public class Task : IAsyncResult, IDisposable
{
[ThreadStatic]
internal static Task? t_currentTask; // The currently executing task.
internal static int s_taskIdCounter; // static counter used to generate unique task IDs
private int m_taskId; // this task's unique ID. initialized only if it is ever requested
internal Delegate? m_action; // The body of the task. Might be Action<object>, Action<TState> or Action. Or possibly a Func.
// If m_action is set to null it will indicate that we operate in the
// "externally triggered completion" mode, which is exclusively meant
// for the signalling Task<TResult> (aka. promise). In this mode,
// we don't call InnerInvoke() in response to a Wait(), but simply wait on
// the completion event which will be set when the Future class calls Finish().
// But the event would now be signalled if Cancel() is called
internal object? m_stateObject; // A state object that can be optionally supplied, passed to action.
internal TaskScheduler? m_taskScheduler; // The task scheduler this task runs under.
internal volatile int m_stateFlags; // SOS DumpAsync command depends on this name
private Task? ParentForDebugger => m_contingentProperties?.m_parent; // Private property used by a debugger to access this Task's parent
private int StateFlagsForDebugger => m_stateFlags; // Private property used by a debugger to access this Task's state flags
// State constants for m_stateFlags;
// The bits of m_stateFlags are allocated as follows:
// 0x40000000 - TaskBase state flag
// 0x3FFF0000 - Task state flags
// 0x0000FF00 - internal TaskCreationOptions flags
// 0x000000FF - publicly exposed TaskCreationOptions flags
//
// See TaskCreationOptions for bit values associated with TaskCreationOptions
//
private const int OptionsMask = 0xFFFF; // signifies the Options portion of m_stateFlags bin: 0000 0000 0000 0000 1111 1111 1111 1111
internal const int TASK_STATE_STARTED = 0x10000; // bin: 0000 0000 0000 0001 0000 0000 0000 0000
internal const int TASK_STATE_DELEGATE_INVOKED = 0x20000; // bin: 0000 0000 0000 0010 0000 0000 0000 0000
internal const int TASK_STATE_DISPOSED = 0x40000; // bin: 0000 0000 0000 0100 0000 0000 0000 0000
internal const int TASK_STATE_EXCEPTIONOBSERVEDBYPARENT = 0x80000; // bin: 0000 0000 0000 1000 0000 0000 0000 0000
internal const int TASK_STATE_CANCELLATIONACKNOWLEDGED = 0x100000; // bin: 0000 0000 0001 0000 0000 0000 0000 0000
internal const int TASK_STATE_FAULTED = 0x200000; // bin: 0000 0000 0010 0000 0000 0000 0000 0000
internal const int TASK_STATE_CANCELED = 0x400000; // bin: 0000 0000 0100 0000 0000 0000 0000 0000
internal const int TASK_STATE_WAITING_ON_CHILDREN = 0x800000; // bin: 0000 0000 1000 0000 0000 0000 0000 0000
internal const int TASK_STATE_RAN_TO_COMPLETION = 0x1000000; // bin: 0000 0001 0000 0000 0000 0000 0000 0000
internal const int TASK_STATE_WAITINGFORACTIVATION = 0x2000000; // bin: 0000 0010 0000 0000 0000 0000 0000 0000
internal const int TASK_STATE_COMPLETION_RESERVED = 0x4000000; // bin: 0000 0100 0000 0000 0000 0000 0000 0000
internal const int TASK_STATE_WAIT_COMPLETION_NOTIFICATION = 0x10000000; // bin: 0001 0000 0000 0000 0000 0000 0000 0000
// This could be moved to InternalTaskOptions enum
internal const int TASK_STATE_EXECUTIONCONTEXT_IS_NULL = 0x20000000; // bin: 0010 0000 0000 0000 0000 0000 0000 0000
internal const int TASK_STATE_TASKSCHEDULED_WAS_FIRED = 0x40000000; // bin: 0100 0000 0000 0000 0000 0000 0000 0000
// A mask for all of the final states a task may be in.
// SOS DumpAsync command depends on these values.
private const int TASK_STATE_COMPLETED_MASK = TASK_STATE_CANCELED | TASK_STATE_FAULTED | TASK_STATE_RAN_TO_COMPLETION;
// Values for ContingentProperties.m_internalCancellationRequested.
private const int CANCELLATION_REQUESTED = 0x1;
// Can be null, a single continuation, a list of continuations, or s_taskCompletionSentinel,
// in that order. The logic arround this object assumes it will never regress to a previous state.
private volatile object? m_continuationObject; // SOS DumpAsync command depends on this name
// m_continuationObject is set to this when the task completes.
private static readonly object s_taskCompletionSentinel = new object();
// A private flag that would be set (only) by the debugger
// When true the Async Causality logging trace is enabled as well as a dictionary to relate operation ids with Tasks
internal static bool s_asyncDebuggingEnabled; // false by default
// This dictonary relates the task id, from an operation id located in the Async Causality log to the actual
// task. This is to be used by the debugger ONLY. Task in this dictionary represent current active tasks.
private static Dictionary<int, Task>? s_currentActiveTasks;
// These methods are a way to access the dictionary both from this class and for other classes that also
// activate dummy tasks. Specifically the AsyncTaskMethodBuilder and AsyncTaskMethodBuilder<>
internal static bool AddToActiveTasks(Task task)
{
Debug.Assert(task != null, "Null Task objects can't be added to the ActiveTasks collection");
Dictionary<int, Task> activeTasks =
Volatile.Read(ref s_currentActiveTasks) ??
Interlocked.CompareExchange(ref s_currentActiveTasks, new Dictionary<int, Task>(), null) ??
s_currentActiveTasks;
int taskId = task.Id;
lock (activeTasks)
{
activeTasks[taskId] = task;
}
// always return true to keep signature as bool for backwards compatibility
return true;
}
internal static void RemoveFromActiveTasks(Task task)
{
Dictionary<int, Task>? activeTasks = s_currentActiveTasks;
if (activeTasks is null)
return;
int taskId = task.Id;
lock (activeTasks)
{
activeTasks.Remove(taskId);
}
}
// We moved a number of Task properties into this class. The idea is that in most cases, these properties never
// need to be accessed during the life cycle of a Task, so we don't want to instantiate them every time. Once
// one of these properties needs to be written, we will instantiate a ContingentProperties object and set
// the appropriate property.
internal class ContingentProperties
{
// Additional context
internal ExecutionContext? m_capturedContext; // The execution context to run the task within, if any. Only set from non-concurrent contexts.
// Completion fields (exceptions and event)
internal volatile ManualResetEventSlim? m_completionEvent; // Lazily created if waiting is required.
internal volatile TaskExceptionHolder? m_exceptionsHolder; // Tracks exceptions, if any have occurred
// Cancellation fields (token, registration, and internally requested)
internal CancellationToken m_cancellationToken; // Task's cancellation token, if it has one
internal StrongBox<CancellationTokenRegistration>? m_cancellationRegistration; // Task's registration with the cancellation token
internal volatile int m_internalCancellationRequested; // Its own field because multiple threads legally try to set it.
// Parenting fields
// # of active children + 1 (for this task itself).
// Used for ensuring all children are done before this task can complete
// The extra count helps prevent the race condition for executing the final state transition
// (i.e. whether the last child or this task itself should call FinishStageTwo())
internal volatile int m_completionCountdown = 1;
// A list of child tasks that threw an exception (TCEs don't count),
// but haven't yet been waited on by the parent, lazily initialized.
internal volatile List<Task>? m_exceptionalChildren;
// A task's parent, or null if parent-less. Only set during Task construction.
internal Task? m_parent;
/// <summary>
/// Sets the internal completion event.
/// </summary>
internal void SetCompleted()
{
ManualResetEventSlim? mres = m_completionEvent;
if (mres != null) mres.Set();
}
/// <summary>
/// Checks if we registered a CT callback during construction, and unregisters it.
/// This should be called when we know the registration isn't useful anymore. Specifically from Finish() if the task has completed
/// successfully or with an exception.
/// </summary>
internal void UnregisterCancellationCallback()
{
if (m_cancellationRegistration != null)
{
// Harden against ODEs thrown from disposing of the CTR.
// Since the task has already been put into a final state by the time this
// is called, all we can do here is suppress the exception.
try { m_cancellationRegistration.Value.Dispose(); }
catch (ObjectDisposedException) { }
m_cancellationRegistration = null;
}
}
}
// This field will only be instantiated to some non-null value if any ContingentProperties need to be set.
// This will be a ContingentProperties instance or a type derived from it
internal ContingentProperties? m_contingentProperties;
// Special internal constructor to create an already-completed task.
// if canceled==true, create a Canceled task, or else create a RanToCompletion task.
// Constructs the task as already completed
internal Task(bool canceled, TaskCreationOptions creationOptions, CancellationToken ct)
{
int optionFlags = (int)creationOptions;
if (canceled)
{
m_stateFlags = TASK_STATE_CANCELED | TASK_STATE_CANCELLATIONACKNOWLEDGED | optionFlags;
m_contingentProperties = new ContingentProperties() // can't have children, so just instantiate directly
{
m_cancellationToken = ct,
m_internalCancellationRequested = CANCELLATION_REQUESTED,
};
}
else
{
m_stateFlags = TASK_STATE_RAN_TO_COMPLETION | optionFlags;
}
}
/// <summary>Constructor for use with promise-style tasks that aren't configurable.</summary>
internal Task()
{
m_stateFlags = TASK_STATE_WAITINGFORACTIVATION | (int)InternalTaskOptions.PromiseTask;
}
// Special constructor for use with promise-style tasks.
// Added promiseStyle parameter as an aid to the compiler to distinguish between (state,TCO) and
// (action,TCO). It should always be true.
internal Task(object? state, TaskCreationOptions creationOptions, bool promiseStyle)
{
Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
// Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks.
// Also allow RunContinuationsAsynchronously because this is the constructor called by TCS
if ((creationOptions & ~(TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
}
// Only set a parent if AttachedToParent is specified.
if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
{
Task? parent = Task.InternalCurrent;
if (parent != null)
{
EnsureContingentPropertiesInitializedUnsafe().m_parent = parent;
}
}
TaskConstructorCore(null, state, default, creationOptions, InternalTaskOptions.PromiseTask, null);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the Task.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
public Task(Action action)
: this(action, null, null, default, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and <see cref="System.Threading.CancellationToken">CancellationToken</see>.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the Task.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// that will be assigned to the new Task.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
/// <exception cref="System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
public Task(Action action, CancellationToken cancellationToken)
: this(action, null, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and creation options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
public Task(Action action, TaskCreationOptions creationOptions)
: this(action, null, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and creation options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
/// <exception cref="System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(action, null, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and state.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
public Task(Action<object?> action, object? state)
: this(action, state, null, default, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action, state, and options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
public Task(Action<object?> action, object? state, CancellationToken cancellationToken)
: this(action, state, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action, state, and options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
public Task(Action<object?> action, object? state, TaskCreationOptions creationOptions)
: this(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, InternalTaskOptions.None, null)
{
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action, state, and options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
/// <exception cref="System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
public Task(Action<object?> action, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this(action, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
}
/// <summary>
/// An internal constructor used by the factory methods on task and its descendent(s).
/// </summary>
/// <param name="action">An action to execute.</param>
/// <param name="state">Optional state to pass to the action.</param>
/// <param name="parent">Parent of Task.</param>
/// <param name="cancellationToken">A CancellationToken for the task.</param>
/// <param name="scheduler">A task scheduler under which the task will run.</param>
/// <param name="creationOptions">Options to control its execution.</param>
/// <param name="internalOptions">Internal options to control its execution</param>
internal Task(Delegate action, object? state, Task? parent, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler? scheduler)
{
if (action == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
// Keep a link to the parent if attached
if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0)
{
EnsureContingentPropertiesInitializedUnsafe().m_parent = parent;
}
TaskConstructorCore(action, state, cancellationToken, creationOptions, internalOptions, scheduler);
Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
"Captured an ExecutionContext when one was already captured.");
CapturedContext = ExecutionContext.Capture();
}
/// <summary>
/// Common logic used by the following internal ctors:
/// Task()
/// Task(object action, object state, Task parent, TaskCreationOptions options, TaskScheduler taskScheduler)
/// </summary>
/// <param name="action">Action for task to execute.</param>
/// <param name="state">Object to which to pass to action (may be null)</param>
/// <param name="scheduler">Task scheduler on which to run thread (only used by continuation tasks).</param>
/// <param name="cancellationToken">A CancellationToken for the Task.</param>
/// <param name="creationOptions">Options to customize behavior of Task.</param>
/// <param name="internalOptions">Internal options to customize behavior of Task.</param>
internal void TaskConstructorCore(Delegate? action, object? state, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler? scheduler)
{
m_action = action;
m_stateObject = state;
m_taskScheduler = scheduler;
// Check for validity of options
if ((creationOptions &
~(TaskCreationOptions.AttachedToParent |
TaskCreationOptions.LongRunning |
TaskCreationOptions.DenyChildAttach |
TaskCreationOptions.HideScheduler |
TaskCreationOptions.PreferFairness |
TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
}
#if DEBUG
// Check the validity of internalOptions
int illegalInternalOptions =
(int)(internalOptions &
~(InternalTaskOptions.PromiseTask |
InternalTaskOptions.ContinuationTask |
InternalTaskOptions.LazyCancellation |
InternalTaskOptions.QueuedByRuntime));
Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
#endif
// Assign options to m_stateAndOptionsFlag.
Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
int tmpFlags = (int)creationOptions | (int)internalOptions; // one write to the volatile m_stateFlags instead of two when setting the above options
m_stateFlags = m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0 ?
tmpFlags | TASK_STATE_WAITINGFORACTIVATION :
tmpFlags;
// Now is the time to add the new task to the children list
// of the creating task if the options call for it.
// We can safely call the creator task's AddNewChild() method to register it,
// because at this point we are already on its thread of execution.
ContingentProperties? props = m_contingentProperties;
if (props != null)
{
Task? parent = props.m_parent;
if (parent != null
&& ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
&& ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0))
{
parent.AddNewChild();
}
}
// if we have a non-null cancellationToken, allocate the contingent properties to save it
// we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags
if (cancellationToken.CanBeCanceled)
{
Debug.Assert((internalOptions & InternalTaskOptions.ContinuationTask) == 0, "TaskConstructorCore: Did not expect to see cancelable token for continuation task.");
AssignCancellationToken(cancellationToken, null, null);
}
}
/// <summary>
/// Handles everything needed for associating a CancellationToken with a task which is being constructed.
/// This method is meant to be called either from the TaskConstructorCore or from ContinueWithCore.
/// </summary>
private void AssignCancellationToken(CancellationToken cancellationToken, Task? antecedent, TaskContinuation? continuation)
{
// There is no need to worry about concurrency issues here because we are in the constructor path of the task --
// there should not be any race conditions to set m_contingentProperties at this point.
ContingentProperties props = EnsureContingentPropertiesInitializedUnsafe();
props.m_cancellationToken = cancellationToken;
try
{
// If an unstarted task has a valid CancellationToken that gets signalled while the task is still not queued
// we need to proactively cancel it, because it may never execute to transition itself.
// The only way to accomplish this is to register a callback on the CT.
// We exclude Promise tasks from this, because TaskCompletionSource needs to fully control the inner tasks's lifetime (i.e. not allow external cancellations)
if (((InternalTaskOptions)Options &
(InternalTaskOptions.QueuedByRuntime | InternalTaskOptions.PromiseTask | InternalTaskOptions.LazyCancellation)) == 0)
{
if (cancellationToken.IsCancellationRequested)
{
// Fast path for an already-canceled cancellationToken
InternalCancel();
}
else
{
// Regular path for an uncanceled cancellationToken
CancellationTokenRegistration ctr;
if (antecedent == null)
{
// if no antecedent was specified, use this task's reference as the cancellation state object
ctr = cancellationToken.UnsafeRegister(static t => ((Task)t!).InternalCancel(), this);
}
else
{
Debug.Assert(continuation != null);
// If an antecedent was specified, pack this task, its antecedent and the TaskContinuation together as a tuple
// and use it as the cancellation state object. This will be unpacked in the cancellation callback so that
// antecedent.RemoveCancellation(continuation) can be invoked.
ctr = cancellationToken.UnsafeRegister(static t =>
{
var tuple = (TupleSlim<Task, Task, TaskContinuation>)t!;
Task targetTask = tuple.Item1;
Task antecedentTask = tuple.Item2;
antecedentTask.RemoveContinuation(tuple.Item3);
targetTask.InternalCancel();
}, new TupleSlim<Task, Task, TaskContinuation>(this, antecedent, continuation));
}
props.m_cancellationRegistration = new StrongBox<CancellationTokenRegistration>(ctr);
}
}
}
catch
{
// If we have an exception related to our CancellationToken, then we need to subtract ourselves
// from our parent before throwing it.
Task? parent = m_contingentProperties?.m_parent;
if ((parent != null) &&
((Options & TaskCreationOptions.AttachedToParent) != 0)
&& ((parent.Options & TaskCreationOptions.DenyChildAttach) == 0))
{
parent.DisregardChild();
}
throw;
}
}
// Debugger support
private string DebuggerDisplayMethodDescription => m_action?.Method.ToString() ?? "{null}";
// Internal property to process TaskCreationOptions access and mutation.
internal TaskCreationOptions Options => OptionsMethod(m_stateFlags);
// Similar to Options property, but allows for the use of a cached flags value rather than
// a read of the volatile m_stateFlags field.
internal static TaskCreationOptions OptionsMethod(int flags)
{
Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
return (TaskCreationOptions)(flags & OptionsMask);
}
// Atomically OR-in newBits to m_stateFlags, while making sure that
// no illegalBits are set. Returns true on success, false on failure.
internal bool AtomicStateUpdate(int newBits, int illegalBits)
{
int oldFlags = m_stateFlags;
return
(oldFlags & illegalBits) == 0 &&
(Interlocked.CompareExchange(ref m_stateFlags, oldFlags | newBits, oldFlags) == oldFlags ||
AtomicStateUpdateSlow(newBits, illegalBits));
}
private bool AtomicStateUpdateSlow(int newBits, int illegalBits)
{
int flags = m_stateFlags;
while (true)
{
if ((flags & illegalBits) != 0) return false;
int oldFlags = Interlocked.CompareExchange(ref m_stateFlags, flags | newBits, flags);
if (oldFlags == flags)
{
return true;
}
flags = oldFlags;
}
}
internal bool AtomicStateUpdate(int newBits, int illegalBits, ref int oldFlags)
{
int flags = oldFlags = m_stateFlags;
while (true)
{
if ((flags & illegalBits) != 0) return false;
oldFlags = Interlocked.CompareExchange(ref m_stateFlags, flags | newBits, flags);
if (oldFlags == flags)
{
return true;
}
flags = oldFlags;
}
}
/// <summary>
/// Sets or clears the TASK_STATE_WAIT_COMPLETION_NOTIFICATION state bit.
/// The debugger sets this bit to aid it in "stepping out" of an async method body.
/// If enabled is true, this must only be called on a task that has not yet been completed.
/// If enabled is false, this may be called on completed tasks.
/// Either way, it should only be used for promise-style tasks.
/// </summary>
/// <param name="enabled">true to set the bit; false to unset the bit.</param>
internal void SetNotificationForWaitCompletion(bool enabled)
{
Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
"Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need
if (enabled)
{
// Atomically set the TASK_STATE_WAIT_COMPLETION_NOTIFICATION bit
bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION,
TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED);
Debug.Assert(success, "Tried to set enabled on completed Task");
}
else
{
// Atomically clear the TASK_STATE_WAIT_COMPLETION_NOTIFICATION bit
Interlocked.And(ref m_stateFlags, ~TASK_STATE_WAIT_COMPLETION_NOTIFICATION);
}
}
/// <summary>
/// Calls the debugger notification method if the right bit is set and if
/// the task itself allows for the notification to proceed.
/// </summary>
/// <returns>true if the debugger was notified; otherwise, false.</returns>
internal bool NotifyDebuggerOfWaitCompletionIfNecessary()
{
// Notify the debugger if of any of the tasks we've waited on requires notification
if (IsWaitNotificationEnabled && ShouldNotifyDebuggerOfWaitCompletion)
{
NotifyDebuggerOfWaitCompletion();
return true;
}
return false;
}
/// <summary>Returns true if any of the supplied tasks require wait notification.</summary>
/// <param name="tasks">The tasks to check.</param>
/// <returns>true if any of the tasks require notification; otherwise, false.</returns>
internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task?[] tasks)
{
Debug.Assert(tasks != null, "Expected non-null array of tasks");
foreach (Task? task in tasks)
{
if (task != null &&
task.IsWaitNotificationEnabled &&
task.ShouldNotifyDebuggerOfWaitCompletion) // potential recursion
{
return true;
}
}
return false;
}
/// <summary>Gets whether either the end await bit is set or (not xor) the task has not completed successfully.</summary>
/// <returns>(DebuggerBitSet || !RanToCompletion)</returns>
internal bool IsWaitNotificationEnabledOrNotRanToCompletion
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (m_stateFlags & (Task.TASK_STATE_WAIT_COMPLETION_NOTIFICATION | Task.TASK_STATE_RAN_TO_COMPLETION))
!= Task.TASK_STATE_RAN_TO_COMPLETION;
}
/// <summary>
/// Determines whether we should inform the debugger that we're ending a join with a task.
/// This should only be called if the debugger notification bit is set, as it is has some cost,
/// namely it is a virtual call (however calling it if the bit is not set is not functionally
/// harmful). Derived implementations may choose to only conditionally call down to this base
/// implementation.
/// </summary>
internal virtual bool ShouldNotifyDebuggerOfWaitCompletion // ideally would be familyAndAssembly, but that can't be done in C#
{
get
{
// It's theoretically possible but extremely rare that this assert could fire because the
// bit was unset between the time that it was checked and this method was called.
// It's so remote a chance that it's worth having the assert to protect against misuse.
bool isWaitNotificationEnabled = IsWaitNotificationEnabled;
Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
return isWaitNotificationEnabled;
}
}
/// <summary>Gets whether the task's debugger notification for wait completion bit is set.</summary>
/// <returns>true if the bit is set; false if it's not set.</returns>
internal bool IsWaitNotificationEnabled => // internal only to enable unit tests; would otherwise be private
(m_stateFlags & TASK_STATE_WAIT_COMPLETION_NOTIFICATION) != 0;
/// <summary>Placeholder method used as a breakpoint target by the debugger. Must not be inlined or optimized.</summary>
/// <remarks>All joins with a task should end up calling this if their debugger notification bit is set.</remarks>
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
private void NotifyDebuggerOfWaitCompletion()
{
// It's theoretically possible but extremely rare that this assert could fire because the
// bit was unset between the time that it was checked and this method was called.
// It's so remote a chance that it's worth having the assert to protect against misuse.
Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
// Now that we're notifying the debugger, clear the bit. The debugger should do this anyway,
// but this adds a bit of protection in case it fails to, and given that the debugger is involved,
// the overhead here for the interlocked is negligable. We do still rely on the debugger
// to clear bits, as this doesn't recursively clear bits in the case of, for example, WhenAny.
SetNotificationForWaitCompletion(enabled: false);
}
// Atomically mark a Task as started while making sure that it is not canceled.
internal bool MarkStarted()
{
return AtomicStateUpdate(TASK_STATE_STARTED, TASK_STATE_CANCELED | TASK_STATE_STARTED);
}
internal void FireTaskScheduledIfNeeded(TaskScheduler ts)
{
if ((m_stateFlags & Task.TASK_STATE_TASKSCHEDULED_WAS_FIRED) == 0)
{
m_stateFlags |= Task.TASK_STATE_TASKSCHEDULED_WAS_FIRED;
if (TplEventSource.Log.IsEnabled())
{
Task? currentTask = Task.InternalCurrent;
Task? parentTask = m_contingentProperties?.m_parent;
TplEventSource.Log.TaskScheduled(ts.Id, currentTask == null ? 0 : currentTask.Id,
this.Id, parentTask == null ? 0 : parentTask.Id, (int)this.Options);
}
}
}
/// <summary>
/// Internal function that will be called by a new child task to add itself to
/// the children list of the parent (this).
///
/// Since a child task can only be created from the thread executing the action delegate
/// of this task, reentrancy is neither required nor supported. This should not be called from
/// anywhere other than the task construction/initialization codepaths.
/// </summary>
internal void AddNewChild()
{
Debug.Assert(Task.InternalCurrent == this, "Task.AddNewChild(): Called from an external context");
ContingentProperties props = EnsureContingentPropertiesInitialized();
if (props.m_completionCountdown == 1)
{
// A count of 1 indicates so far there was only the parent, and this is the first child task
// Single kid => no fuss about who else is accessing the count. Let's save ourselves 100 cycles
props.m_completionCountdown++;
}
else
{
// otherwise do it safely
Interlocked.Increment(ref props.m_completionCountdown);
}
}
// This is called in the case where a new child is added, but then encounters a CancellationToken-related exception.
// We need to subtract that child from m_completionCountdown, or the parent will never complete.
internal void DisregardChild()
{
Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
ContingentProperties props = EnsureContingentPropertiesInitialized();
Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
Interlocked.Decrement(ref props.m_completionCountdown);
}
/// <summary>
/// Starts the <see cref="Task"/>, scheduling it for execution to the current <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </summary>
/// <remarks>
/// A task may only be started and run only once. Any attempts to schedule a task a second time
/// will result in an exception.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
public void Start()
{
Start(TaskScheduler.Current);
}
/// <summary>
/// Starts the <see cref="Task"/>, scheduling it for execution to the specified <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </summary>
/// <remarks>
/// A task may only be started and run only once. Any attempts to schedule a task a second time will
/// result in an exception.
/// </remarks>
/// <param name="scheduler">
/// The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> with which to associate
/// and execute this task.
/// </param>
/// <exception cref="ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
public void Start(TaskScheduler scheduler)
{
// Read the volatile m_stateFlags field once and cache it for subsequent operations
int flags = m_stateFlags;
// Need to check this before (m_action == null) because completed tasks will
// set m_action to null. We would want to know if this is the reason that m_action == null.
if (IsCompletedMethod(flags))
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_TaskCompleted);
}
if (scheduler == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
TaskCreationOptions options = OptionsMethod(flags);
if ((options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_Promise);
}
if ((options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) != 0)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_ContinuationTask);
}
// Make sure that Task only gets started once. Or else throw an exception.
if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_AlreadyStarted);
}
ScheduleAndStart(true);
}
/// <summary>
/// Runs the <see cref="Task"/> synchronously on the current <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </summary>
/// <remarks>
/// <para>
/// A task may only be started and run only once. Any attempts to schedule a task a second time will
/// result in an exception.
/// </para>
/// <para>
/// Tasks executed with <see cref="RunSynchronously()"/> will be associated with the current <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </para>
/// <para>
/// If the target scheduler does not support running this Task on the current thread, the Task will
/// be scheduled for execution on the scheduler, and the current thread will block until the
/// Task has completed execution.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
public void RunSynchronously()
{
InternalRunSynchronously(TaskScheduler.Current, waitForCompletion: true);
}
/// <summary>
/// Runs the <see cref="Task"/> synchronously on the <see
/// cref="System.Threading.Tasks.TaskScheduler">scheduler</see> provided.
/// </summary>