How to catch exceptions from Action containing anonymous method in c#?
10,128
Task myactTask = Task.Factory.StartNew( ( ) => myact);
This does not execute your action, it is a function that returns a reference to your Action.
Task myactTask = Task.Factory.StartNew(myact);
This will execute it and throw/catch the exception.
Author by
User1551892
Updated on June 04, 2022Comments
-
User1551892 almost 2 years
Could any one explain, why am I not getting exception from blow code:
Action <Exception> myact = ( ) => { throw new Exception( "test" ); }; Task myactTask = Task.Factory.StartNew( ( ) => myact); try { myactTask.Wait( ); Console.WriteLine( myactTask.Id.ToString( ) ); Console.WriteLine( myactTask.IsCompleted.ToString( ) ); } catch( AggregateException ex ) { throw ex; }
on the other hand if replace Action "myact" with method "myact()" then I can get exception and it can be handeled with try catch block.
public static void myact( ) { throw new Exception( "test" ); }