|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ |
| 6 | +// |
| 7 | +// |
| 8 | +// |
| 9 | +// Compiler-targeted type for switching back into the current execution context, e.g. |
| 10 | +// |
| 11 | +// await Task.Yield(); |
| 12 | +// ===================== |
| 13 | +// var $awaiter = Task.Yield().GetAwaiter(); |
| 14 | +// if (!$awaiter.IsCompleted) |
| 15 | +// { |
| 16 | +// $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); |
| 17 | +// return; |
| 18 | +// Label: |
| 19 | +// } |
| 20 | +// $awaiter.GetResult(); |
| 21 | +// |
| 22 | +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- |
| 23 | + |
| 24 | +using System; |
| 25 | +using System.Security; |
| 26 | +using System.Diagnostics; |
| 27 | +using System.Diagnostics.Tracing; |
| 28 | +using System.Threading; |
| 29 | +using System.Threading.Tasks; |
| 30 | + |
| 31 | +namespace System.Runtime.CompilerServices |
| 32 | +{ |
| 33 | + // NOTE: YieldAwaitable currently has no state; while developers are encouraged to use Task.Yield() to produce one, |
| 34 | + // no validation is performed to ensure that the developer isn't doing "await new YieldAwaitable()". Such validation |
| 35 | + // would require additional, useless state to be stored, and as this is a type in the CompilerServices namespace, and |
| 36 | + // as the above example isn't harmful, we take the cheaper approach of not validating anything. |
| 37 | + |
| 38 | + /// <summary>Provides an awaitable context for switching into a target environment.</summary> |
| 39 | + /// <remarks>This type is intended for compiler use only.</remarks> |
| 40 | + public readonly struct YieldAwaitable |
| 41 | + { |
| 42 | + /// <summary>Gets an awaiter for this <see cref="YieldAwaitable"/>.</summary> |
| 43 | + /// <returns>An awaiter for this awaitable.</returns> |
| 44 | + /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> |
| 45 | + public YieldAwaiter GetAwaiter() { return new YieldAwaiter(); } |
| 46 | + |
| 47 | + /// <summary>Provides an awaiter that switches into a target environment.</summary> |
| 48 | + /// <remarks>This type is intended for compiler use only.</remarks> |
| 49 | + public readonly struct YieldAwaiter : ICriticalNotifyCompletion |
| 50 | + { |
| 51 | + /// <summary>Gets whether a yield is not required.</summary> |
| 52 | + /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> |
| 53 | + public bool IsCompleted { get { return false; } } // yielding is always required for YieldAwaiter, hence false |
| 54 | + |
| 55 | + /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary> |
| 56 | + /// <param name="continuation">The action to invoke asynchronously.</param> |
| 57 | + /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> |
| 58 | + public void OnCompleted(Action continuation) |
| 59 | + { |
| 60 | + QueueContinuation(continuation, flowContext: true); |
| 61 | + } |
| 62 | + |
| 63 | + /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary> |
| 64 | + /// <param name="continuation">The action to invoke asynchronously.</param> |
| 65 | + /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> |
| 66 | + public void UnsafeOnCompleted(Action continuation) |
| 67 | + { |
| 68 | + QueueContinuation(continuation, flowContext: false); |
| 69 | + } |
| 70 | + |
| 71 | + /// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary> |
| 72 | + /// <param name="continuation">The action to invoke asynchronously.</param> |
| 73 | + /// <param name="flowContext">true to flow ExecutionContext; false if flowing is not required.</param> |
| 74 | + /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> |
| 75 | + private static void QueueContinuation(Action continuation, bool flowContext) |
| 76 | + { |
| 77 | + // Validate arguments |
| 78 | + if (continuation == null) throw new ArgumentNullException(nameof(continuation)); |
| 79 | + |
| 80 | + if (TplEtwProvider.Log.IsEnabled()) |
| 81 | + { |
| 82 | + continuation = OutputCorrelationEtwEvent(continuation); |
| 83 | + } |
| 84 | + // Get the current SynchronizationContext, and if there is one, |
| 85 | + // post the continuation to it. However, treat the base type |
| 86 | + // as if there wasn't a SynchronizationContext, since that's what it |
| 87 | + // logically represents. |
| 88 | + var syncCtx = SynchronizationContext.Current; |
| 89 | + if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext)) |
| 90 | + { |
| 91 | + syncCtx.Post(s_sendOrPostCallbackRunAction, continuation); |
| 92 | + } |
| 93 | + else |
| 94 | + { |
| 95 | + // If we're targeting the default scheduler, queue to the thread pool, so that we go into the global |
| 96 | + // queue. As we're going into the global queue, we might as well use QUWI, which for the global queue is |
| 97 | + // just a tad faster than task, due to a smaller object getting allocated and less work on the execution path. |
| 98 | + TaskScheduler scheduler = TaskScheduler.Current; |
| 99 | + if (scheduler == TaskScheduler.Default) |
| 100 | + { |
| 101 | + if (flowContext) |
| 102 | + { |
| 103 | + ThreadPool.QueueUserWorkItem(s_waitCallbackRunAction, continuation); |
| 104 | + } |
| 105 | + else |
| 106 | + { |
| 107 | + ThreadPool.UnsafeQueueUserWorkItem(s_waitCallbackRunAction, continuation); |
| 108 | + } |
| 109 | + } |
| 110 | + // We're targeting a custom scheduler, so queue a task. |
| 111 | + else |
| 112 | + { |
| 113 | + Task.Factory.StartNew(continuation, default(CancellationToken), TaskCreationOptions.PreferFairness, scheduler); |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + private static Action OutputCorrelationEtwEvent(Action continuation) |
| 119 | + { |
| 120 | +#if CORERT |
| 121 | + // TODO |
| 122 | + return continuation; |
| 123 | +#else |
| 124 | + int continuationId = Task.NewId(); |
| 125 | + Task currentTask = Task.InternalCurrent; |
| 126 | + // fire the correlation ETW event |
| 127 | + TplEtwProvider.Log.AwaitTaskContinuationScheduled(TaskScheduler.Current.Id, (currentTask != null) ? currentTask.Id : 0, continuationId); |
| 128 | + |
| 129 | + return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, (innerContinuation,continuationIdTask) => |
| 130 | + { |
| 131 | + var etwLog = TplEtwProvider.Log; |
| 132 | + etwLog.TaskWaitContinuationStarted(((Task<int>)continuationIdTask).Result); |
| 133 | + |
| 134 | + // ETW event for Task Wait End. |
| 135 | + Guid prevActivityId = new Guid(); |
| 136 | + // Ensure the continuation runs under the correlated activity ID generated above |
| 137 | + if (etwLog.TasksSetActivityIds) |
| 138 | + EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(((Task<int>)continuationIdTask).Result), out prevActivityId); |
| 139 | + |
| 140 | + // Invoke the original continuation provided to OnCompleted. |
| 141 | + innerContinuation(); |
| 142 | + // Restore activity ID |
| 143 | + |
| 144 | + if (etwLog.TasksSetActivityIds) |
| 145 | + EventSource.SetCurrentThreadActivityId(prevActivityId); |
| 146 | + |
| 147 | + etwLog.TaskWaitContinuationComplete(((Task<int>)continuationIdTask).Result); |
| 148 | + }, Task.FromResult(continuationId)); // pass the ID in a task to avoid a closure\ |
| 149 | +#endif |
| 150 | + } |
| 151 | + |
| 152 | + /// <summary>WaitCallback that invokes the Action supplied as object state.</summary> |
| 153 | + private static readonly WaitCallback s_waitCallbackRunAction = RunAction; |
| 154 | + /// <summary>SendOrPostCallback that invokes the Action supplied as object state.</summary> |
| 155 | + private static readonly SendOrPostCallback s_sendOrPostCallbackRunAction = RunAction; |
| 156 | + |
| 157 | + /// <summary>Runs an Action delegate provided as state.</summary> |
| 158 | + /// <param name="state">The Action delegate to invoke.</param> |
| 159 | + private static void RunAction(object state) { ((Action)state)(); } |
| 160 | + |
| 161 | + /// <summary>Ends the await operation.</summary> |
| 162 | + public void GetResult() { } // Nop. It exists purely because the compiler pattern demands it. |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments