[corlib] CoreRT System.Threading.Tasks (#6672)
[mono-project.git] / mcs / class / corlib / corert / Task.cs
blob61f0a1407ddf79e8939d3eb3d1fc89fb53d1ac14
1 using System.Collections.Generic;
2 using System.Collections.ObjectModel;
3 using System.Diagnostics;
4 using System.Runtime.CompilerServices;
5 using System.Diagnostics.Contracts;
6 using System.Security;
7 using System.Security.Permissions;
9 namespace System.Threading.Tasks
11 // these members were copied from https://github.com/mono/mono/blob/7b4dfeebc40cf8c027819b8b7bd85a4e7c87ad50/mcs/class/referencesource/mscorlib/system/threading/Tasks/Task.cs#L220-L246
12 partial class Task
14 // This dictonary relates the task id, from an operation id located in the Async Causality log to the actual
15 // task. This is to be used by the debugger ONLY. Task in this dictionary represent current active tasks.
16 private static readonly Dictionary<int, Task> s_currentActiveTasks = new Dictionary<int, Task> ();
17 private static readonly Object s_activeTasksLock = new Object ();
19 // These methods are a way to access the dictionary both from this class and for other classes that also
20 // activate dummy tasks. Specifically the AsyncTaskMethodBuilder and AsyncTaskMethodBuilder<>
21 [FriendAccessAllowed]
22 internal static bool AddToActiveTasks (Task task)
24 Contract.Requires (task != null, "Null Task objects can't be added to the ActiveTasks collection");
25 lock (s_activeTasksLock)
27 s_currentActiveTasks[task.Id] = task;
29 //always return true to keep signature as bool for backwards compatibility
30 return true;
33 [FriendAccessAllowed]
34 internal static void RemoveFromActiveTasks (int taskId)
36 lock (s_activeTasksLock)
38 s_currentActiveTasks.Remove (taskId);
42 public void MarkAborted (ThreadAbortException e) {}
44 // Copied from reference-sources
45 [SecurityCritical]
46 void ExecuteWithThreadLocal (ref Task currentTaskSlot)
48 // Remember the current task so we can restore it after running, and then
49 Task previousTask = currentTaskSlot;
50 try
52 // place the current task into TLS.
53 currentTaskSlot = this;
55 ExecutionContext ec = CapturedContext;
56 if (ec == null)
58 // No context, just run the task directly.
59 Execute ();
61 else
63 // Run the task. We need a simple shim that converts the
64 // object back into a Task object, so that we can Execute it.
66 // Lazily initialize the callback delegate; benign ----
67 var callback = s_ecCallback;
68 if (callback == null) s_ecCallback = callback = new ContextCallback (ExecutionContextCallback);
69 #if PFX_LEGACY_3_5
70 ExecutionContext.Run (ec, callback, this);
71 #else
72 ExecutionContext.Run (ec, callback, this, true);
73 #endif
76 if (AsyncCausalityTracer.LoggingOn)
77 AsyncCausalityTracer.TraceSynchronousWorkCompletion (CausalityTraceLevel.Required, CausalitySynchronousWork.Execution);
79 Finish (true);
81 finally
83 currentTaskSlot = previousTask;