Last active
May 3, 2018 09:58
-
-
Save SirRufo/6864efd14422610b8d60b68476d7c910 to your computer and use it in GitHub Desktop.
LongRunningOperationWithCancellationTokenAsync
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
private static async Task<decimal> LongRunningOperationWithCancellationTokenAsync( int loop, CancellationToken cancellationToken ) | |
{ | |
// We create a TaskCompletionSource of decimal | |
var taskCompletionSource = new TaskCompletionSource<decimal>(); | |
// Registering a lambda into the cancellationToken | |
cancellationToken.Register( () => | |
{ | |
// We received a cancellation message, cancel the TaskCompletionSource.Task | |
taskCompletionSource.TrySetCanceled(); | |
} ); | |
var task = LongRunningOperation( loop ); | |
// Wait for the first task to finish among the two | |
var completedTask = await Task.WhenAny( task, taskCompletionSource.Task ); | |
return await completedTask; // enough is enough | |
/* the following lines are not needed anymore | |
// If the completed task is our long running operation we set its result. | |
if ( completedTask == task ) | |
{ | |
// Extract the result, the task is finished and the await will return immediately | |
var result = await task; | |
// Set the taskCompletionSource result | |
taskCompletionSource.TrySetResult( result ); | |
} | |
// Return the result of the TaskCompletionSource.Task | |
return await taskCompletionSource.Task; | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment