Advertisement
Guest User

Observed/Unobserved C# async Exceptions

a guest
May 9th, 2014
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void Main()
  2. {
  3.     AppDomain.CurrentDomain.FirstChanceException += (object obj, FirstChanceExceptionEventArgs args) => {
  4.         Console.WriteLine ("First chance exception ");
  5.         args.Dump();
  6.     };
  7.    
  8.     AppDomain.CurrentDomain.UnhandledException += (object obj, UnhandledExceptionEventArgs args) => {
  9.         Console.WriteLine ("Unhandled exception ");
  10.     };
  11.    
  12.     TaskScheduler.UnobservedTaskException += (object obj, UnobservedTaskExceptionEventArgs args) => {
  13.         Console.WriteLine ("Unobserved exception");
  14.     };
  15.    
  16.     try
  17.     {          
  18.         //DoStuff().Wait(); // Observed
  19.         DoStuff();          // Unobserved - Generates a FirstChanceException and an UnobservedTaskException (after several seconds).
  20.     }
  21.     catch (Exception ex)
  22.     {
  23.         Console.WriteLine ("An Observed task.");
  24.     }
  25. }
  26.  
  27. async Task DoStuff()
  28. {
  29.     Task t = Task.FromResult(1);
  30.    
  31.     await t;
  32.    
  33.     throw new ArgumentException();
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement