Skip to content

Instantly share code, notes, and snippets.

@patriksvensson
Last active September 24, 2019 09:11
Show Gist options
  • Save patriksvensson/622adff5f76dccc81749b28baf7dd399 to your computer and use it in GitHub Desktop.
Save patriksvensson/622adff5f76dccc81749b28baf7dd399 to your computer and use it in GitHub Desktop.
Can someone explain this like you would to a 4 year old? πŸ˜…
Doing stuff
Doing more stuff
Task cancelled (Cancellation requested: False) -> No task exception, No inner exception
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
public static class Program
{
public static async Task Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
try
{
await Task.Run(() =>
{
Console.WriteLine("Doing stuff");
}, cancellationTokenSource.Token)
.ContinueWith(t =>
{
Console.WriteLine("Doing more stuff");
}, cancellationTokenSource.Token)
.ContinueWith(t =>
{
throw new Exception("God damn it");
}, cancellationTokenSource.Token)
// If this continuation is removed, I'll get the normal exception.
.ContinueWith(task =>
{
Console.WriteLine("Completed");
}, cancellationTokenSource.Token, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Current);
}
catch (TaskCanceledException ex)
{
// Always get here.
Console.WriteLine("Task cancelled (Cancellation requested: {0}) -> {1}, {2}",
ex.CancellationToken.IsCancellationRequested,
ex.Task.Exception?.Message ?? "No task exception",
ex.InnerException?.Message ?? "No inner exception");
}
catch (Exception ex)
{
// Will not get here.
Console.WriteLine("Exception: {0}", ex);
}
Console.WriteLine("Press ANY key to quit");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment