Last active
September 24, 2019 09:11
-
-
Save patriksvensson/622adff5f76dccc81749b28baf7dd399 to your computer and use it in GitHub Desktop.
Can someone explain this like you would to a 4 year old? π
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
Doing stuff | |
Doing more stuff | |
Task cancelled (Cancellation requested: False) -> No task exception, No inner exception |
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
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