简体   繁体   English

异步方法MVC中的异常处理。 如何为使用await的方法使用try catch?

[英]Exception handling in async Methods MVC. How to use try catch for method called using await?

     [HttpPost]
 public async Task<JsonResult>    
    {
     await sendNotification(responce);
    }

I want to catch exception occured in sendnotification method. 我想捕获sendnotification方法中发生的异常。 How can I call the same using Task.Factory ?? 如何使用Task.Factory调用相同的对象?

You just write a try / catch block, as such: 您只需编写一个try / catch块,如下所示:

[HttpPost]
public async Task<JsonResult>    
{
  try
  {
    await sendNotification(responce);
  }
  catch (Exception ex)
  {
    ...
  }
}

You don't need Task.Factory for this. 您不需要Task.Factory

Exception Handling of sendNotification() task depends on how the task is coded. sendNotification()任务的异常处理取决于该任务的编码方式。 In one way, above Stephen Cleary's answer is right but not sure it fixes your issue. 在某种程度上,斯蒂芬·克莱里(Stephen Cleary)的回答是正确的,但不确定它是否可以解决您的问题。

You can go through below easy understandable articles to understand Exception Handling in Async programming... 您可以阅读以下简单易懂的文章,以了解异步编程中的异常处理...

Basic exception handling in Asynchronious programming in C#. C#异步编程中的基本异常处理。

Exception object behaves differently while handling exceptions in parallel tasks in Asynchronous programming. 在异步编程中,在并行任务中处理异常时,异常对象的行为有所不同。

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

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