简体   繁体   English

如何在c#中捕获包含匿名方法的Action中的异常?

[英]How to catch exceptions from Action containing anonymous method in c#?

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. 另一方面,如果使用方法“myact()”替换Action“myact”,那么我可以获得异常,并且可以使用try catch块进行处理。

public static void myact( ) {
  throw new Exception( "test" );
}
Task myactTask = Task.Factory.StartNew( ( ) => myact);

This does not execute your action, it is a function that returns a reference to your Action. 这不会执行您的操作,它是一个返回对您的Action的引用的函数。

Task myactTask = Task.Factory.StartNew(myact);

This will execute it and throw/catch the exception. 这将执行它并抛出/捕获异常。

This happens because you're catching only a AggregateException not a Exception . 发生这种情况是因为您只捕获AggregateException而不是Exception Another problem is that you're not really executing your code on Task.Factory.StartNew . 另一个问题是你并没有真正在Task.Factory.StartNew上执行你的代码。

Change your code to something like: 将您的代码更改为:

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(Exception ex) {
    throw ex;
}

I coppied the code and it didn't compile however most of the answers are correct, it is down to what you are trying to catch. 我修改了代码并且它没有编译但是大部分答案都是正确的,这取决于你想要捕获的内容。

//Action<in Exception> : Make the delgate take an exception, then throw it
Action<Exception> myact = (ex => { throw ex; });
//Pass a new Exception with the message test "Test" that will be thrown
Task myactTask = Task.Factory.StartNew(() => myact(new Exception("Test")));
try
{
  myactTask.Wait();
  Console.WriteLine(myactTask.Id.ToString());
  Console.WriteLine(myactTask.IsCompleted.ToString());
}
catch (Exception ex)
{
  //Writes out "Test"
  Console.WriteLine(ex.Message);
  throw ex;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM