publicvoidStart<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { // when start, call stateMachine's MoveNext directly. stateMachine.MoveNext(); }
public Task<TResult> Task { get { if (task == null) { // internal task creation(same as TaskCompletionSource but avoid tcs allocation) task = new Task<TResult>(); } return task.Task; } }
publicvoidAwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { // at first await, copy struct state machine to heap(boxed). if (runner == null) { _ = Task; // create TaskCompletionSource // create runner runner = new MoveNextRunner((IAsyncStateMachine)stateMachine); // 这里有装箱成本 } // set cached moveNext delegate(as continuation). awaiter.UnsafeOnCompleted(runner.CachedDelegate); }
publicvoidSetResult(TResult result) { if (task == null) { _ = Task; // create Task task.TrySetResult(result); // same as TaskCompletionSource.TrySetResult. } else { task.TrySetResult(result); } } }
publicclassMoveNextRunner { public Action CachedDelegate;
publicvoidSetResult(T result) { if (runnerPromise == null) { this.result = result; } else { // SetResult signal Task continuation, it will call task.GetResult and finally return to pool self. runnerPromise.SetResult(result);