Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SirRufo/6864efd14422610b8d60b68476d7c910 to your computer and use it in GitHub Desktop.
Save SirRufo/6864efd14422610b8d60b68476d7c910 to your computer and use it in GitHub Desktop.
LongRunningOperationWithCancellationTokenAsync
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