Skip to content

Instantly share code, notes, and snippets.

@AArnott
Last active May 1, 2020 21:40
Show Gist options
  • Save AArnott/4608941 to your computer and use it in GitHub Desktop.
Save AArnott/4608941 to your computer and use it in GitHub Desktop.
Converts .NET TPL async task pattern to the APM pattern. See [Stephen Toub's blog post](http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx)
// LICENSED under the Ms-PL (http://opensource.org/licenses/MS-PL)
public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback callback, object state) {
if (task == null) {
throw new ArgumentNullException("task");
}
if (task.AsyncState == state) {
if (callback != null) {
task.ContinueWith(
(t, cb) => ((AsyncCallback)cb)(t),
callback,
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
}
return task;
}
var tcs = new TaskCompletionSource<TResult>(state);
task.ContinueWith(
t => {
if (t.IsFaulted) {
tcs.TrySetException(t.Exception.InnerExceptions);
} else if (t.IsCanceled) {
tcs.TrySetCanceled();
} else {
tcs.TrySetResult(t.Result);
}
if (callback != null) {
callback(tcs.Task);
}
},
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
return tcs.Task;
}
public static Task ToApm(this Task task, AsyncCallback callback, object state) {
if (task == null) {
throw new ArgumentNullException("task");
}
if (task.AsyncState == state) {
if (callback != null) {
task.ContinueWith(
(t, cb) => ((AsyncCallback)cb)(t),
callback,
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
}
return task;
}
var tcs = new TaskCompletionSource<object>(state);
task.ContinueWith(
t => {
if (t.IsFaulted) {
tcs.TrySetException(t.Exception.InnerExceptions);
} else if (t.IsCanceled) {
tcs.TrySetCanceled();
} else {
tcs.TrySetResult(null);
}
if (callback != null) {
callback(tcs.Task);
}
},
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
return tcs.Task;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment