[coop] Temporarily restore MonoThreadInfo when TLS destructor runs. Fixes #43099
[mono.git] / mcs / class / referencesource / System.Web / TaskAsyncHelper.cs
1 //------------------------------------------------------------------------------
2 // <copyright file="TaskAsyncHelper.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>                                                                
5 //------------------------------------------------------------------------------
6
7 /*
8  * Assists in converting an method written using the Task Asynchronous Pattern to a Begin/End method pair.
9  * 
10  * Copyright (c) 2010 Microsoft Corporation
11  */
12
13 namespace System.Web {
14     using System;
15     using System.Threading.Tasks;
16
17     internal static class TaskAsyncHelper {
18
19         internal static IAsyncResult BeginTask(Func<Task> taskFunc, AsyncCallback callback, object state) {
20             Task task = taskFunc();
21             if (task == null) {
22                 // Something went wrong - let our caller handle it.
23                 return null;
24             }
25
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);
31
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();
39             }
40
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);
49                 }
50                 else {
51                     task.ContinueWith(_ => callback(resultToReturn));
52                 }
53             }
54
55             return resultToReturn;
56         }
57
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) {
61             if (ar == null) {
62                 throw new ArgumentNullException("ar");
63             }
64
65             // Make sure the incoming parameter is actually the correct type.
66             TaskWrapperAsyncResult taskWrapper = ar as TaskWrapperAsyncResult;
67             if (taskWrapper == null) {
68                 // extraction failed
69                 throw new ArgumentException(SR.GetString(SR.TaskAsyncHelper_ParameterInvalid), "ar");
70             }
71
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();
77         }
78
79     }
80 }