Last active
August 29, 2015 14:19
-
-
Save sevenate/538196adb1187d4cfa8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <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