使用Task.Factory时捕获错误

twa*_*ron 20 .net c# multithreading

我正在使用以下内容

Task.Factory.StartNew(() => DoPrintConfigPage(serial));
Run Code Online (Sandbox Code Playgroud)

然后我调用的函数看起来像这样

private void DoPrintConfigPage(string serial) 
{ 
    //do printing work 
}
Run Code Online (Sandbox Code Playgroud)

我的问题是在线程内部抛出异常并且没有被处理.

我试过用try catch包装它

try
{
    Task.Factory.StartNew(() => DoPrintConfigPage(serial));
}
catch (Exception ex) { }
Run Code Online (Sandbox Code Playgroud)

但它仍然没有捕获错误,从而导致应用程序崩溃.

如何在主线程中捕获异常以便我可以处理它们?

更新

我已经做了下面推荐的更改,但仍然说这个例外是未处理的

var task =  Task.Factory.StartNew(() => DoPrintConfigPage(serial))
                               .ContinueWith(tsk =>
                               {
                                  MessageBox.Show("something broke");
                               },TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)

然后在我的DoConfigPage我添加另一个尝试捕获.

在这个问题现在崩溃,并说抛出的异常是未处理的,我错过了什么?

private void DoPrintConfigPage(string serial)
{
    try
    {
        //call the print function
    }
    catch (Exception ex)
    {
        throw ex;   //it is crashing here and saying it is unhandled
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试了Eric J.所提出的相同结果

var task = Task.Factory.StartNew(() => DoPrintConfigPage(serial));

try
{
    task.Wait();                  
}
catch (AggregateException ex) { MessageBox.Show("something broke"); }
Run Code Online (Sandbox Code Playgroud)

Jer*_*all 36

或者,您可以链接创建任务并添加ContinueWith:

var job = Task.Factory
    .StartNew(...)
    .ContinueWith(tsk => 
         {
              // check tsk for exception and handle
         });
Run Code Online (Sandbox Code Playgroud)

编辑:此代码段在运行时会弹出消息框给我:

void Main()
{
    var serial = "some serial";
    var task =  Task.Factory
        .StartNew(() => DoPrintConfigPage(serial))
        .ContinueWith(tsk =>
        {
            MessageBox.Show("something broke");
            var flattened = tsk.Exception.Flatten();

            // NOTE: Don't actually handle exceptions this way, m'kay?
            flattened.Handle(ex => { MessageBox.Show("Error:" + ex.Message); return true;});
        },TaskContinuationOptions.OnlyOnFaulted);

}

public void DoPrintConfigPage(string serial)
{
    throw new Exception("BOOM!");
}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是你可以添加`TaskContinuationOptions.OnlyOnFaulted`参数,这样只有在有异常的情况下才会运行延续,从而有效地使它像`catch`块一样运行. (9认同)

Eri*_* J. 10

try启动新任务后立即退出您的块,因为该方法将继续运行.

相反,您可以将Exception作为AggregateException捕获,等待任务(或多个任务)完成:

var task1 = Task.Factory.StartNew(() =>
{
    throw new MyCustomException("I'm bad, but not too bad!");
});

try
{
    task1.Wait();
}
catch (AggregateException ae)
{
    // Assume we know what's going on with this particular exception. 
    // Rethrow anything else. AggregateException.Handle provides 
    // another way to express this. See later example. 
    foreach (var e in ae.InnerExceptions)
    {
        if (e is MyCustomException)
        {
            Console.WriteLine(e.Message);
        }
        else
        {
            throw;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/dd997415.aspx


sǝɯ*_*ɯɐſ 7

如果您没有等待任务,我认为最简单的解决方案是在Task.Exception中找到:

获取导致Task过早结束的AggregateException.如果任务成功完成或尚未抛出任何异常,则返回null.

我使用的是这样的东西:

Task.Factory.StartNew(() => DoStuffHere())
    .ContinueWith(task =>
    {
        if (task.Exception != null)
            Log("log all the exceptions!");
    });
Run Code Online (Sandbox Code Playgroud)