2015-10-26 175 views
0

我目前调用async方法,不想await它。我不需要async方法的结果,也不希望在IO期间阻塞。但是,如果在async方法中出现错误,我想catch吧。到目前为止,我有:调用异步方法而不等待

public static void main() { 
    MyAsyncMethod(). 
    ContinueWith(t => Console.WriteLine(t.Exception), 
      TaskContinuationOptions.OnlyOnFaulted); 
    //dostuff without waiting for result 
} 

这不是赶上从MainMyAyncMethod引发的异常。有什么我做错了吗?

+0

有没有try-catch块...? – Tim

+0

如果它“不捕捉异常”会发生什么? – i3arnon

+0

我认为Continuewith会“捕捉”异常。至少,这是我读的,但目前我的代码崩溃 – user3750474

回答

1

async-await和ContinueWith可以工作,但它充满了头痛。将错误处理重构为一个方法并将其放入该方法非常简单,然后您可以从主方法调用该新方法。

public static void main() { 
    var task = DoMyAsyncMethod(); 

    //dostuff without waiting for result 

    //Do a wait at the end to prevent the program from closing before the background work completes. 
    task.Wait(); 

} 

private static async Task DoMyAsyncMethod() 
{ 
    try 
    { 
     await MyAsyncMethod(); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 
} 

我怀疑你是在处理真正的问题是,缺少Wait()和程序之前您的后台工作收盘本身是做处理。

+0

我们的程序将永远在服务器上运行,所以我们永远不会等待。这不会在DoMyAsyncMethod中阻塞吗? – user3750474

+0

不,当你点击'await'时,'DoMyAsyncMethod'函数会重新调用'Task'对象,它不会阻塞。这取决于你想用这个'Task'来完成,等待它,扔掉它,没关系。 'await'实际上只是一个用'ContinueWith'完成工作的简单方法,它可以让你用写同步代码的方式编写异步代码(例如,使用try/catch而不是'ContinueWith(SomeMethod,TaskContinuationOptions .OnlyOnFaulted)')。 –