如何在同步方法中从Task.Run()捕获异常

时间:2019-08-14 20:04:15

标签: c# asynchronous exception error-handling async-await

由于要使用的框架的限制,必须从同步方法中调用Task.Run。因此,我迫不及待地等待Task.Run,从而使异常处理变得更加棘手。如何确保捕获到Task.Run调用中的逻辑生成的任何异常并从Start()返回false?

当前我的代码因吞咽异常而挂起,并且Start()从未完成。

这是我代码的当前逻辑。

// this method must be synchronous :(
protected bool Start()
{
    try
    {
        //setup some things

        // time for async, can't block here
        Task.Run(() => StartAsyncStuff()).ContinueWith(t =>
        {
            // this is not being triggered
            if (t.IsFaulted)
                throw t.Exception;
        }, TaskContinuationOptions.OnlyOnFaulted);

        // wait for changes caused by StartAsyncStuff() in external application
        while (someCondition)
        {
            // check some things, but not too often!
            Thread.Sleep(10000);
        }
        // if all changes are good
        return true;
    }
    catch(Exception ex)
    {
        // changes failed, do something with ex
        myLogger.error() // this doesn't log!
        return false;
    }
}

private async Task StartAsyncStuff()
{
    try
    {
        await SomeEvenMoreAsyncStuff();
    }
    catch (Exception ex)
    { 
        myLogger.error() // this logs!
        throw new Exception("Add some more detail", ex);
    }
}

private async Task SomeEvenMoreAsyncStuff()
{

    // check some things 

    if (timeout)
    {
        myLogger.error() // this logs!
        throw new Exception("Timeout caused badThing")!
    }
}

0 个答案:

没有答案
相关问题