1 //------------------------------------------------------------------------------
2 // <copyright file="TaskAsyncHelper.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 //------------------------------------------------------------------------------
8 * Assists in converting an method written using the Task Asynchronous Pattern to a Begin/End method pair.
10 * Copyright (c) 2010 Microsoft Corporation
13 namespace System.Web {
15 using System.Threading.Tasks;
17 internal static class TaskAsyncHelper {
19 internal static IAsyncResult BeginTask(Func<Task> taskFunc, AsyncCallback callback, object state) {
20 Task task = taskFunc();
22 // Something went wrong - let our caller handle it.
26 // We need to wrap the inner Task so that the IAsyncResult exposed by this method
27 // has the state object that was provided as a parameter. We could be a bit smarter
28 // about this to save an allocation if the state objects are equal, but that's a
29 // micro-optimization.
30 TaskWrapperAsyncResult resultToReturn = new TaskWrapperAsyncResult(task, state);
32 // Task instances are always marked CompletedSynchronously = false, even if the
33 // operation completed synchronously. We should detect this and modify the IAsyncResult
34 // we pass back to our caller as appropriate. Only read the 'IsCompleted' property once
35 // to avoid a race condition where the underlying Task completes during this method.
36 bool actuallyCompletedSynchronously = task.IsCompleted;
37 if (actuallyCompletedSynchronously) {
38 resultToReturn.ForceCompletedSynchronously();
41 if (callback != null) {
42 // ContinueWith() is a bit slow: it captures execution context and hops threads. We should
43 // avoid calling it and just invoke the callback directly if the underlying Task is
44 // already completed. Only use ContinueWith as a fallback. There's technically a ---- here
45 // in that the Task may have completed between the check above and the call to
46 // ContinueWith below, but ContinueWith will do the right thing in both cases.
47 if (actuallyCompletedSynchronously) {
48 callback(resultToReturn);
51 task.ContinueWith(_ => callback(resultToReturn));
55 return resultToReturn;
58 // The parameter is named 'ar' since it matches the parameter name on the EndEventHandler delegate type,
59 // and we expect that most consumers will end up invoking this method via an instance of that delegate.
60 internal static void EndTask(IAsyncResult ar) {
62 throw new ArgumentNullException("ar");
65 // Make sure the incoming parameter is actually the correct type.
66 TaskWrapperAsyncResult taskWrapper = ar as TaskWrapperAsyncResult;
67 if (taskWrapper == null) {
69 throw new ArgumentException(SR.GetString(SR.TaskAsyncHelper_ParameterInvalid), "ar");
72 // The End* method doesn't actually perform any actual work, but we do need to maintain two invariants:
73 // 1. Make sure the underlying Task actually *is* complete.
74 // 2. If the Task encountered an exception, observe it here.
75 // (TaskAwaiter.GetResult() handles both of those, and it rethrows the original exception rather than an AggregateException.)
76 taskWrapper.Task.GetAwaiter().GetResult();