/
JoinableTaskDependencyGraph.cs
1116 lines (984 loc) · 57.6 KB
/
JoinableTaskDependencyGraph.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.Threading
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
/// <summary>
/// Methods to maintain dependencies between <see cref="JoinableTask"/>.
/// Those methods are expected to be called by <see cref="JoinableTask"/> or <see cref="JoinableTaskCollection"/> only to maintain relationship between them, and should not be called directly by other code.
/// </summary>
internal static class JoinableTaskDependencyGraph
{
private static readonly HashSet<IJoinableTaskDependent> EmptySet = new HashSet<IJoinableTaskDependent>();
/// <summary>
/// Gets a value indicating whether there is no child depenent item.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal static bool HasNoChildDependentNode(IJoinableTaskDependent taskItem)
{
Requires.NotNull(taskItem, nameof(taskItem));
Assumes.True(Monitor.IsEntered(taskItem.JoinableTaskContext.SyncContextLock));
return taskItem.GetJoinableTaskDependentData().HasNoChildDependentNode;
}
/// <summary>
/// Checks whether a task or collection is a directly dependent of this item.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal static bool HasDirectDependency(IJoinableTaskDependent taskItem, IJoinableTaskDependent dependency)
{
Requires.NotNull(taskItem, nameof(taskItem));
Assumes.True(Monitor.IsEntered(taskItem.JoinableTaskContext.SyncContextLock));
return taskItem.GetJoinableTaskDependentData().HasDirectDependency(dependency);
}
/// <summary>
/// Gets a value indicating whether the main thread is waiting for the task's completion.
/// </summary>
internal static bool HasMainThreadSynchronousTaskWaiting(IJoinableTaskDependent taskItem)
{
Requires.NotNull(taskItem, nameof(taskItem));
using (taskItem.JoinableTaskContext.NoMessagePumpSynchronizationContext.Apply())
{
lock (taskItem.JoinableTaskContext.SyncContextLock)
{
return taskItem.GetJoinableTaskDependentData().HasMainThreadSynchronousTaskWaiting(taskItem);
}
}
}
/// <summary>
/// Gets a likely value whether the main thread is blocked for the caller's completion.
/// </summary>
internal static bool MaybeHasMainThreadSynchronousTaskWaiting(IJoinableTaskDependent taskItem)
{
return taskItem.GetJoinableTaskDependentData().MaybeHasMainThreadSynchronousTaskWaiting();
}
/// <summary>
/// Adds a <see cref="JoinableTaskDependentData"/> instance as one that is relevant to the async operation.
/// </summary>
/// <param name="taskItem">The current joinableTask or collection.</param>
/// <param name="joinChild">The <see cref="IJoinableTaskDependent"/> to join as a child.</param>
internal static JoinableTaskCollection.JoinRelease AddDependency(IJoinableTaskDependent taskItem, IJoinableTaskDependent joinChild)
{
Requires.NotNull(taskItem, nameof(taskItem));
return JoinableTaskDependentData.AddDependency(taskItem, joinChild);
}
/// <summary>
/// Removes a <see cref="IJoinableTaskDependent"/> instance as one that is no longer relevant to the async operation.
/// </summary>
/// <param name="taskItem">The current joinableTask or collection.</param>
/// <param name="child">The <see cref="IJoinableTaskDependent"/> to join as a child.</param>
/// <param name="forceCleanup">Ignore refCount, it is being used when the child task is completed.</param>
internal static void RemoveDependency(IJoinableTaskDependent taskItem, IJoinableTaskDependent child, bool forceCleanup = false)
{
Requires.NotNull(taskItem, nameof(taskItem));
JoinableTaskDependentData.RemoveDependency(taskItem, child, forceCleanup);
}
/// <summary>
/// Gets all dependent nodes registered in the dependency collection.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal static IEnumerable<IJoinableTaskDependent> GetDirectDependentNodes(IJoinableTaskDependent taskItem)
{
Requires.NotNull(taskItem, nameof(taskItem));
Assumes.True(Monitor.IsEntered(taskItem.JoinableTaskContext.SyncContextLock));
return taskItem.GetJoinableTaskDependentData().GetDirectDependentNodes();
}
/// <summary>
/// Check whether a task is being tracked in our tracking list.
/// </summary>
internal static bool IsDependingSynchronousTask(IJoinableTaskDependent taskItem, JoinableTask syncTask)
{
Requires.NotNull(taskItem, nameof(taskItem));
return taskItem.GetJoinableTaskDependentData().IsDependingSynchronousTask(syncTask);
}
/// <summary>
/// Calculate the collection of events we need trigger after we enqueue a request.
/// This method is expected to be used with the JTF lock.
/// </summary>
/// <param name="taskItem">The current joinableTask or collection.</param>
/// <param name="forMainThread">True if we want to find tasks to process the main thread queue. Otherwise tasks to process the background queue.</param>
/// <returns>The collection of synchronous tasks we need notify.</returns>
internal static IReadOnlyCollection<JoinableTask> GetDependingSynchronousTasks(IJoinableTaskDependent taskItem, bool forMainThread)
{
Requires.NotNull(taskItem, nameof(taskItem));
Assumes.True(Monitor.IsEntered(taskItem.JoinableTaskContext.SyncContextLock));
return taskItem.GetJoinableTaskDependentData().GetDependingSynchronousTasks(forMainThread);
}
/// <summary>
/// Gets a snapshot of all joined tasks.
/// FOR DIAGNOSTICS COLLECTION ONLY.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal static IEnumerable<JoinableTask> GetAllDirectlyDependentJoinableTasks(IJoinableTaskDependent taskItem)
{
Requires.NotNull(taskItem, nameof(taskItem));
return JoinableTaskDependentData.GetAllDirectlyDependentJoinableTasks(taskItem);
}
/// <summary>
/// Recursively adds this joinable and all its dependencies to the specified set, that are not yet completed.
/// </summary>
internal static void AddSelfAndDescendentOrJoinedJobs(IJoinableTaskDependent taskItem, HashSet<JoinableTask> joinables)
{
Requires.NotNull(taskItem, nameof(taskItem));
JoinableTaskDependentData.AddSelfAndDescendentOrJoinedJobs(taskItem, joinables);
}
/// <summary>
/// When the current dependent node is a synchronous task, this method is called before the thread is blocked to wait it to complete.
/// This adds the current task to the dependingSynchronousTaskTracking list of the task itself (which will propergate through its dependencies.)
/// After the task is finished, <see cref="OnSynchronousTaskEndToBlockWaiting"/> is called to revert this change.
/// This method is expected to be used with the JTF lock.
/// </summary>
/// <param name="taskItem">The current joinableTask or collection.</param>
/// <param name="taskHasPendingRequests">Return the JoinableTask which has already had pending requests to be handled.</param>
/// <param name="pendingRequestsCount">The number of pending requests.</param>
internal static void OnSynchronousTaskStartToBlockWaiting(JoinableTask taskItem, out JoinableTask? taskHasPendingRequests, out int pendingRequestsCount)
{
Requires.NotNull(taskItem, nameof(taskItem));
Assumes.True(Monitor.IsEntered(taskItem.Factory.Context.SyncContextLock));
JoinableTaskDependentData.OnSynchronousTaskStartToBlockWaiting(taskItem, out taskHasPendingRequests, out pendingRequestsCount);
}
/// <summary>
/// When the current dependent node is a synchronous task, this method is called after the synchronous is completed, and the thread is no longer blocked.
/// This removes the current task from the dependingSynchronousTaskTracking list of the task itself (and propergate through its dependencies.)
/// It reverts the data structure change done in the <see cref="OnSynchronousTaskStartToBlockWaiting"/>.
/// </summary>
internal static void OnSynchronousTaskEndToBlockWaiting(JoinableTask taskItem)
{
Requires.NotNull(taskItem, nameof(taskItem));
JoinableTaskDependentData.OnSynchronousTaskEndToBlockWaiting(taskItem);
}
/// <summary>
/// Remove all synchronous tasks tracked by the this task.
/// This is called when this task is completed.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal static void OnTaskCompleted(IJoinableTaskDependent taskItem)
{
Requires.NotNull(taskItem, nameof(taskItem));
Assumes.True(Monitor.IsEntered(taskItem.JoinableTaskContext.SyncContextLock));
taskItem.GetJoinableTaskDependentData().OnTaskCompleted(taskItem);
}
/// <summary>
/// Get all tasks inside the candidate sets tasks, which are depended by one or more task in the source tasks list.
/// </summary>
/// <param name="sourceTasks">A collection of JoinableTasks represents source tasks.</param>
/// <param name="candidateTasks">A collection of JoinableTasks which represents candidates.</param>
/// <returns>A set of tasks matching the condition.</returns>
internal static HashSet<JoinableTask> GetDependentTasksFromCandidates(IEnumerable<JoinableTask> sourceTasks, IEnumerable<JoinableTask> candidateTasks)
{
Requires.NotNull(sourceTasks, nameof(sourceTasks));
Requires.NotNull(candidateTasks, nameof(candidateTasks));
var candidates = new HashSet<JoinableTask>(candidateTasks);
if (candidates.Count == 0)
{
return candidates;
}
var results = new HashSet<JoinableTask>();
var visited = new HashSet<IJoinableTaskDependent>();
var queue = new Queue<IJoinableTaskDependent>();
foreach (JoinableTask task in sourceTasks)
{
if (task != null && visited.Add(task))
{
queue.Enqueue(task);
}
}
while (queue.Count > 0)
{
IJoinableTaskDependent startDepenentNode = queue.Dequeue();
if (candidates.Contains(startDepenentNode))
{
results.Add((JoinableTask)startDepenentNode);
}
lock (startDepenentNode.JoinableTaskContext.SyncContextLock)
{
foreach (IJoinableTaskDependent? dependentItem in JoinableTaskDependencyGraph.GetDirectDependentNodes(startDepenentNode))
{
if (visited.Add(dependentItem))
{
queue.Enqueue(dependentItem);
}
}
}
}
return results;
}
/// <summary>
/// Computes dependency graph to clean up all potential unreachable dependents items.
/// </summary>
/// <param name="syncTask">A thread blocking sychornizing task.</param>
/// <param name="allReachableNodes">Returns all reachable nodes in the connected dependency graph, if unreachable dependency is found.</param>
/// <returns>True if it removes any unreachable items.</returns>
internal static bool CleanUpPotentialUnreachableDependentItems(JoinableTask syncTask, [NotNullWhen(true)] out HashSet<IJoinableTaskDependent>? allReachableNodes)
{
Requires.NotNull(syncTask, nameof(syncTask));
// a set of tasks may form a dependent loop, so it will make the reference count system
// not to work correctly when we try to remove the synchronous task.
// To get rid of those loops, if a task still tracks the synchronous task after reducing
// the reference count, we will calculate the entire reachable tree from the root. That will
// tell us the exactly tasks which need track the synchronous task, and we will clean up the rest.
HashSet<IJoinableTaskDependent>? possibleUnreachableItems = syncTask.PotentialUnreachableDependents;
if (possibleUnreachableItems is object && possibleUnreachableItems.Count > 0)
{
var reachableNodes = new HashSet<IJoinableTaskDependent>();
IJoinableTaskDependent syncTaskItem = syncTask;
JoinableTaskDependentData.ComputeSelfAndDescendentOrJoinedJobsAndRemainTasks(syncTaskItem, reachableNodes, possibleUnreachableItems);
allReachableNodes = reachableNodes;
// force to remove all invalid items
if (possibleUnreachableItems.Count > 0)
{
JoinableTaskDependentData.RemoveUnreachableDependentItems(syncTask, possibleUnreachableItems, reachableNodes);
possibleUnreachableItems.Clear();
return true;
}
}
allReachableNodes = null;
return false;
}
/// <summary>
/// Force to clean up all unreachable dependent item, so they are not marked to block the syncTask.
/// </summary>
/// <param name="syncTask">The thread blocking task.</param>
/// <param name="unreachableItems">Unreachable dependent items.</param>
/// <param name="reachableItems">All reachable items.</param>
internal static void RemoveUnreachableDependentItems(JoinableTask syncTask, HashSet<IJoinableTaskDependent> unreachableItems, HashSet<IJoinableTaskDependent> reachableItems)
{
Requires.NotNull(syncTask, nameof(syncTask));
Requires.NotNull(unreachableItems, nameof(unreachableItems));
Requires.NotNull(reachableItems, nameof(reachableItems));
JoinableTaskDependentData.RemoveUnreachableDependentItems(syncTask, unreachableItems, reachableItems);
}
/// <summary>
/// Preserve data for the JoinableTask dependency tree. It is holded inside either a <see cref="JoinableTask"/> or a <see cref="JoinableTaskCollection"/>.
/// Do not call methods/properties directly anywhere out of <see cref="JoinableTaskDependencyGraph"/>.
/// </summary>
internal struct JoinableTaskDependentData
{
/// <summary>
/// A map of jobs that we should be willing to dequeue from when we control the UI thread, and a ref count. Lazily constructed.
/// </summary>
/// <remarks>
/// When the value in an entry is decremented to 0, the entry is removed from the map.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Dictionary<IJoinableTaskDependent, int> childDependentNodes;
/// <summary>
/// The head of a singly linked list of records to track which task may process events of this task.
/// This list should contain only tasks which need be completed synchronously, and depends on this task.
/// </summary>
private DependentSynchronousTask? dependingSynchronousTaskTracking;
/// <summary>
/// Gets a value indicating whether the <see cref="childDependentNodes"/> is empty.
/// </summary>
internal bool HasNoChildDependentNode => this.childDependentNodes is null || this.childDependentNodes.Count == 0;
/// <summary>
/// Gets a snapshot of all joined tasks.
/// FOR DIAGNOSTICS COLLECTION ONLY.
/// This method is expected to be used with the JTF lock.
/// </summary>
/// <param name="taskOrCollection">The current joinableTask or collection contains this data.</param>
internal static IEnumerable<JoinableTask> GetAllDirectlyDependentJoinableTasks(IJoinableTaskDependent taskOrCollection)
{
Requires.NotNull(taskOrCollection, nameof(taskOrCollection));
Assumes.True(Monitor.IsEntered(taskOrCollection.JoinableTaskContext.SyncContextLock));
if (taskOrCollection.GetJoinableTaskDependentData().childDependentNodes is null)
{
return Enumerable.Empty<JoinableTask>();
}
var allTasks = new HashSet<JoinableTask>();
AddSelfAndDescendentOrJoinedJobs(taskOrCollection, allTasks);
return allTasks;
}
/// <summary>
/// Adds a <see cref="JoinableTaskDependentData"/> instance as one that is relevant to the async operation.
/// </summary>
/// <param name="parentTaskOrCollection">The current joinableTask or collection contains to add a dependency.</param>
/// <param name="joinChild">The <see cref="IJoinableTaskDependent"/> to join as a child.</param>
internal static JoinableTaskCollection.JoinRelease AddDependency(IJoinableTaskDependent parentTaskOrCollection, IJoinableTaskDependent joinChild)
{
Requires.NotNull(parentTaskOrCollection, nameof(parentTaskOrCollection));
Requires.NotNull(joinChild, nameof(joinChild));
if (parentTaskOrCollection == joinChild)
{
// Joining oneself would be pointless.
return default(JoinableTaskCollection.JoinRelease);
}
using (parentTaskOrCollection.JoinableTaskContext.NoMessagePumpSynchronizationContext.Apply())
{
List<AsyncManualResetEvent>? eventsNeedNotify = null;
lock (parentTaskOrCollection.JoinableTaskContext.SyncContextLock)
{
var joinableTask = joinChild as JoinableTask;
if (joinableTask?.IsFullyCompleted == true)
{
return default(JoinableTaskCollection.JoinRelease);
}
ref JoinableTaskDependentData data = ref parentTaskOrCollection.GetJoinableTaskDependentData();
if (data.childDependentNodes is null)
{
data.childDependentNodes = new Dictionary<IJoinableTaskDependent, int>(capacity: 2);
}
if (data.childDependentNodes.TryGetValue(joinChild, out int refCount) && !parentTaskOrCollection.NeedRefCountChildDependencies)
{
return default(JoinableTaskCollection.JoinRelease);
}
data.childDependentNodes[joinChild] = ++refCount;
if (refCount == 1)
{
// This constitutes a significant change, so we should apply synchronous task tracking to the new child.
joinChild.OnAddedToDependency(parentTaskOrCollection);
IReadOnlyCollection<PendingNotification>? tasksNeedNotify = AddDependingSynchronousTaskToChild(parentTaskOrCollection, joinChild);
if (tasksNeedNotify.Count > 0)
{
eventsNeedNotify = new List<AsyncManualResetEvent>(tasksNeedNotify.Count);
foreach (PendingNotification taskToNotify in tasksNeedNotify)
{
AsyncManualResetEvent? notifyEvent = taskToNotify.SynchronousTask.RegisterPendingEventsForSynchrousTask(taskToNotify.TaskHasPendingMessages, taskToNotify.NewPendingMessagesCount);
if (notifyEvent is object)
{
eventsNeedNotify.Add(notifyEvent);
}
}
}
parentTaskOrCollection.OnDependencyAdded(joinChild);
}
}
// We explicitly do this outside our lock.
if (eventsNeedNotify is object)
{
foreach (AsyncManualResetEvent? queueEvent in eventsNeedNotify)
{
queueEvent.PulseAll();
}
}
return new JoinableTaskCollection.JoinRelease(parentTaskOrCollection, joinChild);
}
}
/// <summary>
/// Removes a <see cref="IJoinableTaskDependent"/> instance as one that is no longer relevant to the async operation.
/// </summary>
/// <param name="parentTaskOrCollection">The current joinableTask or collection contains to remove a dependency.</param>
/// <param name="joinChild">The <see cref="IJoinableTaskDependent"/> to join as a child.</param>
/// <param name="forceCleanup">Ignore refCount, it is being used when the child task is completed.</param>
internal static void RemoveDependency(IJoinableTaskDependent parentTaskOrCollection, IJoinableTaskDependent joinChild, bool forceCleanup)
{
Requires.NotNull(parentTaskOrCollection, nameof(parentTaskOrCollection));
Requires.NotNull(joinChild, nameof(joinChild));
using (parentTaskOrCollection.JoinableTaskContext.NoMessagePumpSynchronizationContext.Apply())
{
ref JoinableTaskDependentData data = ref parentTaskOrCollection.GetJoinableTaskDependentData();
lock (parentTaskOrCollection.JoinableTaskContext.SyncContextLock)
{
if (data.childDependentNodes is object && data.childDependentNodes.TryGetValue(joinChild, out int refCount))
{
if (refCount == 1 || forceCleanup)
{
joinChild.OnRemovedFromDependency(parentTaskOrCollection);
data.childDependentNodes.Remove(joinChild);
data.RemoveDependingSynchronousTaskFromChild(joinChild);
parentTaskOrCollection.OnDependencyRemoved(joinChild);
// A node with no out-going dependency chain cannot be a part of a circular dependency loop.
// JoinableTaskCollection doesn't have a completion event, this logic makes sure it will be removed from a long runnning JTF.Run.
if (data.HasNoChildDependentNode)
{
DependentSynchronousTask? existingTaskTracking = data.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
existingTaskTracking.SynchronousTask.PotentialUnreachableDependents?.Remove(parentTaskOrCollection);
existingTaskTracking = existingTaskTracking.Next;
}
}
}
else
{
data.childDependentNodes[joinChild] = --refCount;
}
}
}
}
}
/// <summary>
/// Recursively adds this joinable and all its dependencies to the specified set, that are not yet completed.
/// </summary>
/// <param name="taskOrCollection">The current joinableTask or collection contains this data.</param>
/// <param name="joinables">A collection to hold <see cref="JoinableTask"/> found.</param>
internal static void AddSelfAndDescendentOrJoinedJobs(IJoinableTaskDependent taskOrCollection, HashSet<JoinableTask> joinables)
{
Requires.NotNull(taskOrCollection, nameof(taskOrCollection));
Requires.NotNull(joinables, nameof(joinables));
if (taskOrCollection is JoinableTask thisJoinableTask)
{
if (thisJoinableTask.IsCompleteRequested)
{
if (!thisJoinableTask.IsFullyCompleted)
{
joinables.Add(thisJoinableTask);
}
return;
}
if (!joinables.Add(thisJoinableTask))
{
return;
}
}
Dictionary<IJoinableTaskDependent, int>? childDependentNodes = taskOrCollection.GetJoinableTaskDependentData().childDependentNodes;
if (childDependentNodes is object)
{
foreach (KeyValuePair<IJoinableTaskDependent, int> item in childDependentNodes)
{
AddSelfAndDescendentOrJoinedJobs(item.Key, joinables);
}
}
}
/// <summary>
/// When the current dependent node is a synchronous task, this method is called before the thread is blocked to wait it to complete.
/// This adds the current task to the <see cref="dependingSynchronousTaskTracking"/> of the task itself (which will propergate through its dependencies.)
/// After the task is finished, <see cref="OnSynchronousTaskEndToBlockWaiting"/> is called to revert this change.
/// This method is expected to be used with the JTF lock.
/// </summary>
/// <param name="syncTask">The synchronized joinableTask.</param>
/// <param name="taskHasPendingRequests">Return the JoinableTask which has already had pending requests to be handled.</param>
/// <param name="pendingRequestsCount">The number of pending requests.</param>
internal static void OnSynchronousTaskStartToBlockWaiting(JoinableTask syncTask, out JoinableTask? taskHasPendingRequests, out int pendingRequestsCount)
{
Requires.NotNull(syncTask, nameof(syncTask));
pendingRequestsCount = 0;
taskHasPendingRequests = AddDependingSynchronousTask(syncTask, syncTask, ref pendingRequestsCount);
}
/// <summary>
/// When the current dependent node is a synchronous task, this method is called after the synchronous is completed, and the thread is no longer blocked.
/// This removes the current task from the <see cref="dependingSynchronousTaskTracking"/> of the task itself (and propergate through its dependencies.)
/// It reverts the data structure change done in the <see cref="OnSynchronousTaskStartToBlockWaiting"/>.
/// </summary>
/// <param name="syncTask">The synchronized joinableTask.</param>
internal static void OnSynchronousTaskEndToBlockWaiting(JoinableTask syncTask)
{
Requires.NotNull(syncTask, nameof(syncTask));
using (syncTask.Factory.Context.NoMessagePumpSynchronizationContext.Apply())
{
lock (syncTask.Factory.Context.SyncContextLock)
{
// Remove itself from the tracking list, after the task is completed.
IJoinableTaskDependent syncTaskItem = syncTask;
if (syncTaskItem.GetJoinableTaskDependentData().dependingSynchronousTaskTracking is object)
{
RemoveDependingSynchronousTask(syncTask, syncTask, force: true);
}
if (syncTask.PotentialUnreachableDependents is object && syncTask.PotentialUnreachableDependents.Count > 0)
{
RemoveUnreachableDependentItems(syncTask, syncTask.PotentialUnreachableDependents, EmptySet);
syncTask.PotentialUnreachableDependents = null;
}
}
}
}
/// <summary>
/// Compute all reachable nodes from a synchronous task. Because we use the result to clean up invalid
/// items from the remain task, we will remove valid task from the collection, and stop immediately if nothing is left.
/// </summary>
/// <param name="taskOrCollection">The current joinableTask or collection owns the data.</param>
/// <param name="reachableNodes">All reachable dependency nodes. This is not a completed list, if there is no remain node.</param>
/// <param name="remainNodes">Remain dependency nodes we want to check. After the execution, it will retain non-reachable nodes.</param>
internal static void ComputeSelfAndDescendentOrJoinedJobsAndRemainTasks(IJoinableTaskDependent taskOrCollection, HashSet<IJoinableTaskDependent> reachableNodes, HashSet<IJoinableTaskDependent> remainNodes)
{
Requires.NotNull(taskOrCollection, nameof(taskOrCollection));
Requires.NotNull(remainNodes, nameof(remainNodes));
Requires.NotNull(reachableNodes, nameof(reachableNodes));
if ((taskOrCollection as JoinableTask)?.IsFullyCompleted != true)
{
if (reachableNodes.Add(taskOrCollection))
{
if (remainNodes.Remove(taskOrCollection) && remainNodes.Count == 0)
{
// no remain task left, quit the loop earlier
return;
}
if ((taskOrCollection as JoinableTask)?.IsCompleteRequested == true)
{
return;
}
Dictionary<IJoinableTaskDependent, int>? dependencies = taskOrCollection.GetJoinableTaskDependentData().childDependentNodes;
if (dependencies is object)
{
foreach (KeyValuePair<IJoinableTaskDependent, int> item in dependencies)
{
ComputeSelfAndDescendentOrJoinedJobsAndRemainTasks(item.Key, reachableNodes, remainNodes);
if (remainNodes.Count == 0)
{
return;
}
}
}
}
}
}
/// <summary>
/// Force to clean up all unreachable dependent item, so they are not marked to block the syncTask.
/// </summary>
/// <param name="syncTask">The thread blocking task.</param>
/// <param name="unreachableItems">Unreachable dependent items.</param>
/// <param name="reachableItemsReadOnlySet">All reachable items.</param>
internal static void RemoveUnreachableDependentItems(JoinableTask syncTask, HashSet<IJoinableTaskDependent> unreachableItems, HashSet<IJoinableTaskDependent> reachableItemsReadOnlySet)
{
ThreadingEventSource.Instance.CircularJoinableTaskDependencyDetected(unreachableItems.Count, reachableItemsReadOnlySet.Count);
HashSet<IJoinableTaskDependent>? remainPlaceHold = null;
foreach (IJoinableTaskDependent? unreachableItem in unreachableItems)
{
RemoveDependingSynchronousTask(unreachableItem, syncTask, reachableItemsReadOnlySet, ref remainPlaceHold);
}
}
/// <summary>
/// Gets all dependent nodes registered in the <see cref="childDependentNodes"/>
/// This method is expected to be used with the JTF lock.
/// </summary>
internal IEnumerable<IJoinableTaskDependent> GetDirectDependentNodes()
{
if (this.childDependentNodes is null)
{
return Enumerable.Empty<IJoinableTaskDependent>();
}
return this.childDependentNodes.Keys;
}
/// <summary>
/// Checks whether a dependent node is inside <see cref="childDependentNodes"/>.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal bool HasDirectDependency(IJoinableTaskDependent dependency)
{
if (this.childDependentNodes is null)
{
return false;
}
return this.childDependentNodes.ContainsKey(dependency);
}
/// <summary>
/// Gets a value indicating whether the main thread is waiting for the task's completion
/// This method is expected to be used with the JTF lock.
/// </summary>
internal bool HasMainThreadSynchronousTaskWaiting(IJoinableTaskDependent taskItem)
{
DependentSynchronousTask? existingTaskTracking = this.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
DependentSynchronousTask? nextTrackingTask = existingTaskTracking.Next;
if ((existingTaskTracking.SynchronousTask.State & JoinableTask.JoinableTaskFlags.SynchronouslyBlockingMainThread) == JoinableTask.JoinableTaskFlags.SynchronouslyBlockingMainThread)
{
if (existingTaskTracking.SynchronousTask.HasPotentialUnreachableDependents)
{
// This might remove the current tracking item from the linked list, so we capture next node first.
if (!CleanUpPotentialUnreachableDependentItems(existingTaskTracking.SynchronousTask, out HashSet<IJoinableTaskDependent>? allReachableNodes) ||
allReachableNodes.Contains(taskItem))
{
// this task is still a dependenting task
return true;
}
}
else
{
return true;
}
}
existingTaskTracking = nextTrackingTask;
}
return false;
}
/// <summary>
/// Gets a likely value whether the main thread is blocked for the caller's completion.
/// </summary>
internal bool MaybeHasMainThreadSynchronousTaskWaiting()
{
DependentSynchronousTask? existingTaskTracking = this.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
if ((existingTaskTracking.SynchronousTask.State & JoinableTask.JoinableTaskFlags.SynchronouslyBlockingMainThread) == JoinableTask.JoinableTaskFlags.SynchronouslyBlockingMainThread)
{
return true;
}
existingTaskTracking = existingTaskTracking.Next;
}
return false;
}
/// <summary>
/// Remove all synchronous tasks tracked by the this task.
/// This is called when this task is completed.
/// This method is expected to be used with the JTF lock.
/// </summary>
internal void OnTaskCompleted(IJoinableTaskDependent thisDependentNode)
{
if (this.dependingSynchronousTaskTracking is object)
{
DependentSynchronousTask? existingTaskTracking = this.dependingSynchronousTaskTracking;
this.dependingSynchronousTaskTracking = null;
if (this.childDependentNodes is object)
{
Dictionary<IJoinableTaskDependent, int>.KeyCollection? childrenTasks = this.childDependentNodes.Keys;
while (existingTaskTracking is object)
{
RemoveDependingSynchronousTaskFrom(childrenTasks, existingTaskTracking.SynchronousTask, force: existingTaskTracking.SynchronousTask == thisDependentNode);
HashSet<IJoinableTaskDependent>? potentialUnreachableDependents = existingTaskTracking.SynchronousTask.PotentialUnreachableDependents;
if (potentialUnreachableDependents is object && potentialUnreachableDependents.Count > 0)
{
potentialUnreachableDependents.Remove(thisDependentNode);
}
existingTaskTracking = existingTaskTracking.Next;
}
}
}
}
/// <summary>
/// Check whether a task is being tracked in our tracking list.
/// </summary>
internal bool IsDependingSynchronousTask(JoinableTask syncTask)
{
DependentSynchronousTask? existingTaskTracking = this.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
if (existingTaskTracking.SynchronousTask == syncTask)
{
return true;
}
existingTaskTracking = existingTaskTracking.Next;
}
return false;
}
/// <summary>
/// Calculate the collection of events we need trigger after we enqueue a request.
/// This method is expected to be used with the JTF lock.
/// </summary>
/// <param name="forMainThread">True if we want to find tasks to process the main thread queue. Otherwise tasks to process the background queue.</param>
/// <returns>The collection of synchronous tasks we need notify.</returns>
internal IReadOnlyCollection<JoinableTask> GetDependingSynchronousTasks(bool forMainThread)
{
int count = this.CountOfDependingSynchronousTasks();
if (count == 0)
{
return Array.Empty<JoinableTask>();
}
var tasksNeedNotify = new List<JoinableTask>(count);
DependentSynchronousTask? existingTaskTracking = this.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
JoinableTask? syncTask = existingTaskTracking.SynchronousTask;
bool syncTaskInOnMainThread = (syncTask.State & JoinableTask.JoinableTaskFlags.SynchronouslyBlockingMainThread) == JoinableTask.JoinableTaskFlags.SynchronouslyBlockingMainThread;
if (forMainThread == syncTaskInOnMainThread)
{
// Only synchronous tasks are in the list, so we don't need do further check for the CompletingSynchronously flag
tasksNeedNotify.Add(syncTask);
}
existingTaskTracking = existingTaskTracking.Next;
}
return tasksNeedNotify;
}
/// <summary>
/// Applies all synchronous tasks tracked by this task to a new child/dependent task.
/// </summary>
/// <param name="dependentNode">The current joinableTask or collection owns the data.</param>
/// <param name="child">The new child task.</param>
/// <returns>Pairs of synchronous tasks we need notify and the event source triggering it, plus the number of pending events.</returns>
private static IReadOnlyCollection<PendingNotification> AddDependingSynchronousTaskToChild(IJoinableTaskDependent dependentNode, IJoinableTaskDependent child)
{
Requires.NotNull(dependentNode, nameof(dependentNode));
Requires.NotNull(child, nameof(child));
Assumes.True(Monitor.IsEntered(dependentNode.JoinableTaskContext.SyncContextLock));
ref JoinableTaskDependentData data = ref dependentNode.GetJoinableTaskDependentData();
int count = data.CountOfDependingSynchronousTasks();
if (count == 0)
{
return Array.Empty<PendingNotification>();
}
var tasksNeedNotify = new List<PendingNotification>(count);
DependentSynchronousTask? existingTaskTracking = data.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
int totalEventNumber = 0;
JoinableTask? eventTriggeringTask = AddDependingSynchronousTask(child, existingTaskTracking.SynchronousTask, ref totalEventNumber);
if (eventTriggeringTask is object)
{
tasksNeedNotify.Add(new PendingNotification(existingTaskTracking.SynchronousTask, eventTriggeringTask, totalEventNumber));
}
existingTaskTracking = existingTaskTracking.Next;
}
return tasksNeedNotify;
}
/// <summary>
/// Tracks a new synchronous task for this task.
/// A synchronous task is a task blocking a thread and waits it to be completed. We may want the blocking thread
/// to process events from this task.
/// </summary>
/// <param name="taskOrCollection">The current joinableTask or collection.</param>
/// <param name="synchronousTask">The synchronous task.</param>
/// <param name="totalEventsPending">The total events need be processed.</param>
/// <returns>The task causes us to trigger the event of the synchronous task, so it can process new events. Null means we don't need trigger any event.</returns>
private static JoinableTask? AddDependingSynchronousTask(IJoinableTaskDependent taskOrCollection, JoinableTask synchronousTask, ref int totalEventsPending)
{
Requires.NotNull(taskOrCollection, nameof(taskOrCollection));
Requires.NotNull(synchronousTask, nameof(synchronousTask));
Assumes.True(Monitor.IsEntered(taskOrCollection.JoinableTaskContext.SyncContextLock));
JoinableTask? thisJoinableTask = taskOrCollection as JoinableTask;
if (thisJoinableTask is object)
{
if (thisJoinableTask.IsCompleteRequested)
{
if (!thisJoinableTask.IsFullyCompleted)
{
// A completed task might still have pending items in the queue.
int pendingCount = thisJoinableTask.GetPendingEventCountForSynchronousTask(synchronousTask);
if (pendingCount > 0)
{
totalEventsPending += pendingCount;
return thisJoinableTask;
}
}
return null;
}
}
ref JoinableTaskDependentData data = ref taskOrCollection.GetJoinableTaskDependentData();
DependentSynchronousTask? existingTaskTracking = data.dependingSynchronousTaskTracking;
while (existingTaskTracking is object)
{
if (existingTaskTracking.SynchronousTask == synchronousTask)
{
existingTaskTracking.ReferenceCount++;
return null;
}
existingTaskTracking = existingTaskTracking.Next;
}
JoinableTask? eventTriggeringTask = null;
if (thisJoinableTask is object)
{
int pendingItemCount = thisJoinableTask.GetPendingEventCountForSynchronousTask(synchronousTask);
if (pendingItemCount > 0)
{
totalEventsPending += pendingItemCount;
eventTriggeringTask = thisJoinableTask;
}
}
// For a new synchronous task, we need apply it to our child tasks.
var newTaskTracking = new DependentSynchronousTask(synchronousTask)
{
Next = data.dependingSynchronousTaskTracking,
};
Thread.MemoryBarrier();
data.dependingSynchronousTaskTracking = newTaskTracking;
if (data.childDependentNodes is object)
{
foreach (KeyValuePair<IJoinableTaskDependent, int> item in data.childDependentNodes)
{
JoinableTask? childTiggeringTask = AddDependingSynchronousTask(item.Key, synchronousTask, ref totalEventsPending);
if (eventTriggeringTask is null)
{
eventTriggeringTask = childTiggeringTask;
}
}
}
return eventTriggeringTask;
}
/// <summary>
/// Remove a synchronous task from the tracking list.
/// </summary>
/// <param name="taskOrCollection">The current joinableTask or collection.</param>
/// <param name="syncTask">The synchronous task.</param>
/// <param name="force">We always remove it from the tracking list if it is true. Otherwise, we keep tracking the reference count.</param>
private static void RemoveDependingSynchronousTask(IJoinableTaskDependent taskOrCollection, JoinableTask syncTask, bool force = false)
{
Requires.NotNull(taskOrCollection, nameof(taskOrCollection));
Requires.NotNull(syncTask, nameof(syncTask));
Assumes.True(Monitor.IsEntered(taskOrCollection.JoinableTaskContext.SyncContextLock));
RemoveDependingSynchronousTaskFrom(new IJoinableTaskDependent[] { taskOrCollection }, syncTask, force);
}
/// <summary>
/// Remove a synchronous task from the tracking list of a list of tasks.
/// </summary>
/// <param name="tasks">A list of tasks we need update the tracking list.</param>
/// <param name="syncTask">The synchronous task we want to remove.</param>
/// <param name="force">We always remove it from the tracking list if it is true. Otherwise, we keep tracking the reference count.</param>
private static void RemoveDependingSynchronousTaskFrom(IReadOnlyCollection<IJoinableTaskDependent> tasks, JoinableTask syncTask, bool force)
{
Requires.NotNull(tasks, nameof(tasks));
Requires.NotNull(syncTask, nameof(syncTask));
HashSet<IJoinableTaskDependent>? emptySetOrNull = force ? EmptySet : null;
HashSet<IJoinableTaskDependent>? remainNodes = syncTask.PotentialUnreachableDependents;
foreach (IJoinableTaskDependent? task in tasks)
{
RemoveDependingSynchronousTask(task, syncTask, reachableNodesReadOnlySet: emptySetOrNull, ref remainNodes);
}
if (remainNodes is object && remainNodes.Count > 0)
{
if (force)
{
Assumes.NotNull(emptySetOrNull);
Assumes.True(emptySetOrNull.Count == 0);
RemoveUnreachableDependentItems(syncTask, remainNodes, reachableItemsReadOnlySet: emptySetOrNull);
syncTask.PotentialUnreachableDependents = null;
}
else if (syncTask.PotentialUnreachableDependents != remainNodes)
{
// a set of tasks may form a dependent loop, so it will make the reference count system
// not to work correctly when we try to remove the synchronous task.
// It will require full dependency scanning to clean them up, which is quite expensive,
// so we keep tracking them, and clean them up when it becomes essential.
syncTask.PotentialUnreachableDependents = remainNodes;
}
}
}
/// <summary>
/// Remove a synchronous task from the tracking list of this task.
/// </summary>
/// <param name="taskOrCollection">The current joinableTask or collection.</param>
/// <param name="task">The synchronous task.</param>
/// <param name="reachableNodesReadOnlySet">
/// If it is not null, it will contain all dependency nodes which can track the synchronous task. We will ignore reference count in that case.
/// </param>
/// <param name="remainingDependentNodes">This will retain the tasks which still tracks the synchronous task.</param>
private static void RemoveDependingSynchronousTask(IJoinableTaskDependent taskOrCollection, JoinableTask task, HashSet<IJoinableTaskDependent>? reachableNodesReadOnlySet, ref HashSet<IJoinableTaskDependent>? remainingDependentNodes)
{
Requires.NotNull(taskOrCollection, nameof(taskOrCollection));
Requires.NotNull(task, nameof(task));
ref JoinableTaskDependentData data = ref taskOrCollection.GetJoinableTaskDependentData();
DependentSynchronousTask? previousTaskTracking = null;
DependentSynchronousTask? currentTaskTracking = data.dependingSynchronousTaskTracking;
bool removed = false;
while (currentTaskTracking is object)
{
if (currentTaskTracking.SynchronousTask == task)
{
if (--currentTaskTracking.ReferenceCount > 0)
{
if (reachableNodesReadOnlySet is object)
{
if (!reachableNodesReadOnlySet.Contains(taskOrCollection))
{
currentTaskTracking.ReferenceCount = 0;
}
}
}
if (currentTaskTracking.ReferenceCount == 0)
{
removed = true;
if (previousTaskTracking is object)
{
previousTaskTracking.Next = currentTaskTracking.Next;
}
else
{
data.dependingSynchronousTaskTracking = currentTaskTracking.Next;
}
}
if (reachableNodesReadOnlySet is null)
{
// if a node doesn't have dependencies, it cannot be a part of a dependency circle.
if (removed || taskOrCollection.GetJoinableTaskDependentData().HasNoChildDependentNode)
{
if (remainingDependentNodes is object)
{
remainingDependentNodes.Remove(taskOrCollection);
}
}
else
{
if (remainingDependentNodes is null)
{
remainingDependentNodes = new HashSet<IJoinableTaskDependent>();