Skip to content

Instantly share code, notes, and snippets.

@sevenate
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save sevenate/538196adb1187d4cfa8a to your computer and use it in GitHub Desktop.

Select an option

Save sevenate/538196adb1187d4cfa8a to your computer and use it in GitHub Desktop.
/// <summary>
/// Various async/await/task extensions.
/// </summary>
public static class AsyncExtensions
{
/// <summary>
/// Return awaitable task that will be complete right after passed token cancellation.
/// Note: make sure to pass new token instance every time to prevent memory leaks and that this instance will be eventually canceled.
/// Hint: use the provided example how to create and pass the token to the async method with <see cref="WaitForCancellation"/> extension used inside:
/// <example>
/// <![CDATA[
/// var cts = new CancellationTokenSource();
/// cts.CancelAfter(TimeSpan.FromSeconds(5));
/// SomeOperationAsync(cts);
/// ]]>
/// </example>
/// </summary>
/// <param name="token">Token to wait for cancellation.</param>
/// <returns>Awaitable task result.</returns>
public static Task WaitForCancellation(this CancellationToken token)
{
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
token.Register(() =>
{
TaskCompletionSource<bool> tcs = taskCompletionSource;
Task.Factory.StartNew(s => ((TaskCompletionSource<bool>)s).TrySetResult(true),
tcs,
CancellationToken.None,
TaskCreationOptions.PreferFairness,
TaskScheduler.Default);
tcs.Task.Wait();
});
return taskCompletionSource.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment