4

谁能解释一下,为什么我没有从打击代码中得到异常:

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;
  }

另一方面,如果用方法“myact()”替换动作“myact”,那么我可以得到异常,它可以用 try catch 块处理。

public static void myact( ) {
  throw new Exception( "test" );
}
4

3 回答 3

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

这不会执行您的操作,它是一个返回对您的操作的引用的函数。

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

这将执行它并抛出/捕获异常。

于 2013-01-23T12:27:05.787 回答
0

发生这种情况是因为您只捕获 aAggregateException而不是 a Exception。另一个问题是您并没有真正在Task.Factory.StartNew.

将您的代码更改为:

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;
}
于 2013-01-23T12:25:47.820 回答
0

我复制了代码并且它没有编译但是大多数答案都是正确的,这取决于你想要捕捉的内容。

//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;
}
于 2013-01-23T12:31:17.893 回答