private static Task<decimal> LongRunningOperation(int loop)
{
// Start a task a return it
return Task.Run(() =>
{
decimal result = 0;
// Loop for a defined number of iterations
for (int i = 0; i < loop; i++)
{
// Do something that takes times like a Thread.Sleep in .NET Core 2.
Thread.Sleep(1000); // change this string
// add this string
Console.WriteLine(i.ToString());
result += i;
}
return result;
});
}
public static async Task CancelANonCancellableTaskAsync()
{
Console.WriteLine(nameof(CancelANonCancellableTaskAsync));
using (var cancellationTokenSource = new CancellationTokenSource())
{
// Listening to key press to cancel
var keyBoardTask = Task.Run(() =>
{
Console.WriteLine("Press enter to cancel");
Console.ReadKey();
// Sending the cancellation message
cancellationTokenSource.Cancel();
// add this strings
Console.WriteLine("Press enter to exit");
Console.ReadKey();
});
try
{
// Running the long running task
var longRunningTask = LongRunningOperationWithCancellationTokenAsync(100, cancellationTokenSource.Token);
var result = await longRunningTask;
Console.WriteLine("Result {0}", result);
Console.WriteLine("Press enter to continue");
}
catch (TaskCanceledException)
{
Console.WriteLine("Task was cancelled");
}
await keyBoardTask;
}
}
}
And I see that after an attempt to interrupt the execution of the task, the output to the console continues. The task continues to work.