# Thursday, March 31, 2011

Example of TaskSchedular.UnobservedTaskException in action

Today I had a little bit of challenge trying to demonstrate the behavior of TaskSchedular.UnobservedTaskException. TaskSchedular.UnobservedTaskException can be used to deal with any unhandled exception that occurs during the execution of a task. The event fires when the garbage collector tries to clean up the task. My initial code was good, but I forgot to wait for the task to be done before forcing the GC to do its job Smile

The code below is an effective example of how TaskSchedular.UnobservedTaskException works.

1: public  class  Example 
2: {
3:     public  void  Test()
4:     {
5:         Task  t = new  Task ( delegate 
6:         {
7:             Console .WriteLine( "Do test, just before exception."  );
8:             throw  new  Exception ();
9:         } );
10:         t.Start();
11: 
12:     }
13: }
14: 
15: class  Program 
16: {
17:     static  void  Main( string [] args )
18:     {
19:         TaskScheduler .UnobservedTaskException += new  EventHandler <UnobservedTaskExceptionEventArgs >( TaskScheduler_UnobservedTaskException );
20: 
21:         Example  example = new  Example ();
22:         example.Test();
23: 
24:         Thread .Sleep( 2000 ); // delay is needed to make sure the task is done before calling GC. 
25:         Console .WriteLine( "Done sleeping"  );
26: 
27:         GC .Collect();
28:         GC .WaitForPendingFinalizers();
29: 
30:         Console .ReadLine();
31:     }
32: 
33:     static  void  TaskScheduler_UnobservedTaskException( object  sender, UnobservedTaskExceptionEventArgs  e )
34:     {
35:         Console .WriteLine( "Error."  );
36:         e.SetObserved();
37:     }
38: }
39: 
#    Comments [0] |