public
Last active

Async/Await support for .NET 4.0

  • Download Gist
async.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
// Copyright (c) 2012 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
 
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
using System.Threading.Tasks;
 
// This is a minimal implementation of the stuff needed by the C# 5 Beta
// compiler for 'async'/'await' feature.
// Simply add this file to a .NET 4.0 project, and 'async'/'await' will work
// in your code without requiring your users to install .NET 4.5.
// However, you still need the C# 5 compiler for compiling your code.
// Caveats:
// - Stack trace is lost when rethrowing exceptions
// - Unhandled Exceptions in 'async void' methods are re-thrown immediately
// and not posted to the synchronization context
// - Flowing ExecutionContext is not supported
// --> do not use this in security critical code (APTCA)
// - The code is not optimized. Tasks are always created, repeated boxing may occur.
 
namespace System.Threading.Tasks
{
internal static class TaskEx
{
public static TaskAwaiter GetAwaiter(this Task task)
{
return new TaskAwaiter(task);
}
public static TaskAwaiter<T> GetAwaiter<T>(this Task<T> task)
{
return new TaskAwaiter<T>(task);
}
}
internal struct TaskAwaiter : INotifyCompletion
{
readonly Task task;
internal TaskAwaiter(Task task)
{
this.task = task;
}
internal static TaskScheduler TaskScheduler {
get {
if (SynchronizationContext.Current == null)
return TaskScheduler.Default;
else
return TaskScheduler.FromCurrentSynchronizationContext();
}
}
public bool IsCompleted {
get { return task.IsCompleted; }
}
public void OnCompleted(Action continuation)
{
this.task.ContinueWith(
delegate (Task task) {
continuation();
}, TaskAwaiter.TaskScheduler);
}
public void GetResult()
{
try {
task.Wait();
} catch (AggregateException ex) {
throw ex.InnerExceptions[0];
}
}
}
internal struct TaskAwaiter<T> : INotifyCompletion
{
readonly Task<T> task;
internal TaskAwaiter(Task<T> task)
{
this.task = task;
}
public bool IsCompleted {
get { return task.IsCompleted; }
}
public void OnCompleted(Action continuation)
{
this.task.ContinueWith(
delegate (Task<T> task) {
continuation();
}, TaskAwaiter.TaskScheduler);
}
public T GetResult()
{
try {
return task.Result;
} catch (AggregateException ex) {
throw ex.InnerExceptions[0];
}
}
}
}
 
namespace System.Runtime.CompilerServices
{
internal interface INotifyCompletion
{
void OnCompleted(Action continuation);
}
internal interface ICriticalNotifyCompletion : INotifyCompletion
{
[SecurityCritical]
void UnsafeOnCompleted(Action continuation);
}
internal interface IAsyncStateMachine
{
void MoveNext();
void SetStateMachine(IAsyncStateMachine stateMachine);
}
internal struct AsyncVoidMethodBuilder
{
public static AsyncVoidMethodBuilder Create()
{
return new AsyncVoidMethodBuilder();
}
public void SetException(Exception exception)
{
throw exception;
}
public void SetResult()
{
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
// Should not get called as we don't implement the optimization that this method is used for.
throw new NotImplementedException();
}
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
}
internal struct AsyncTaskMethodBuilder
{
TaskCompletionSource<object> tcs;
public Task Task { get { return tcs.Task; } }
public static AsyncTaskMethodBuilder Create()
{
AsyncTaskMethodBuilder b;
b.tcs = new TaskCompletionSource<object>();
return b;
}
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
// Should not get called as we don't implement the optimization that this method is used for.
throw new NotImplementedException();
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
public void SetResult()
{
tcs.SetResult(null);
}
public void SetException(Exception exception)
{
tcs.SetException(exception);
}
}
internal struct AsyncTaskMethodBuilder<T>
{
TaskCompletionSource<T> tcs;
public Task<T> Task { get { return tcs.Task; } }
public static AsyncTaskMethodBuilder<T> Create()
{
AsyncTaskMethodBuilder<T> b;
b.tcs = new TaskCompletionSource<T>();
return b;
}
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
// Should not get called as we don't implement the optimization that this method is used for.
throw new NotImplementedException();
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
awaiter.OnCompleted(stateMachine.MoveNext);
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
AwaitOnCompleted(ref awaiter, ref stateMachine);
}
public void SetResult(T result)
{
tcs.SetResult(result);
}
public void SetException(Exception exception)
{
tcs.SetException(exception);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.