Skip to content

Instantly share code, notes, and snippets.

@tocalai
Created June 17, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tocalai/24b9254cc212cd636d73f12b28754b07 to your computer and use it in GitHub Desktop.
Save tocalai/24b9254cc212cd636d73f12b28754b07 to your computer and use it in GitHub Desktop.
Demonstrate use continue with to handle task exception
class Program
{
static void Main (string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
var t1 = RunTaskWithException ();
// case for handle exception
t1.ContinueWith(_ =>
{
var message = string.Empty;
foreach(var ex in _.Exception.Flatten().InnerExceptions)
{
message += ex.Message + Environment.NewLine;
}
Console.WriteLine($"Catch exception: {message}");
},
TaskContinuationOptions.OnlyOnFaulted
);
// case for continue process other task if t1 got expected execute
t1.ContinueWith(_ =>
{
// ...
Console.WriteLine($"Do other processing");
},
TaskContinuationOptions.OnlyOnRanToCompletion
);
#if (!DEBUG)
Thread.Sleep (1000);
GC.Collect ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
Thread.Sleep (1000);
#endif
Console.WriteLine ("Press any key to exit...");
Console.ReadKey ();
}
private static void TaskScheduler_UnobservedTaskException (object sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved ();
Console.WriteLine ($"Task unobservedTaskExeption occurs {e.Exception}.");
}
private static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine ($"Unhandled exception occurs {e.ExceptionObject}.");
}
private static Task<int> RunTaskWithException () {
return System.Threading.Tasks.Task.Factory.StartNew (() => {
var n1 = 1;
var n2 = 0;
var result = n1 / n2;
return result;
});
}
private static Task<int> RunTaskWithExceptionInnerTryCatch ()
{
return System.Threading.Tasks.Task.Factory.StartNew (() =>
{
try
{
var n1 = 1;
var n2 = 0;
var result = n1 / n2;
return result;
}
catch (Exception ex)
{
Console.WriteLine ($"Exception occurs, {ex.Message}");
return 0;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment