首页 新闻 赞助 找找看

.net async异步方法中的异常如何捕获

0
悬赏园豆:20 [待解决问题]
  public string GetString()
        {
            Thread.Sleep(3000);
            int s = int.Parse("ab");//抛出异常
            return s.ToString();
        }
        public Task<string> GetStringAsync()
        {
            return Task.Run<string>(() => { return GetString(); });
        }
   public async Task<ActionResult> TaskDemo()
        {
            string result = "";
            try
            {
            Task<string> task = GetStringAsync();
           
                result = await task;
            }
            catch (AggregateException ex)
            {
                foreach (Exception inner in ex.InnerExceptions)
                {
                    result += string.Format("Exception type {0} from {1}",
                     inner.GetType(), inner.Source);
                }
            }
            return View(result);
        }

为什么GetString方法中的异常不能被捕获,异步方法中的异常应该如何捕获,上述例子如何进行异常捕获呢?

摆脱菜鸟的主页 摆脱菜鸟 | 初学一级 | 园豆:16
提问于:2016-03-18 14:20
< >
分享
所有回答(4)
0

http://blog.zhaojie.me/2012/04/exception-handling-in-csharp-async-await-1.html

刘宏玺 | 园豆:14020 (专家六级) | 2016-03-18 14:42

大神,这篇文章我看了,可是看的有点糊涂啊!

针对我这个具体情况,如何进行捕获呢,我的方法的问题在哪呢?

支持(0) 反对(0) 摆脱菜鸟 | 园豆:16 (初学一级) | 2016-03-18 15:25
0

 

task.Exception

Launcher | 园豆:45045 (高人七级) | 2016-03-18 15:28

大神,能不能具体点,我对异步不是很熟,刚开始研究,能不能针对我上面的方法,具体如何修改呢?

支持(0) 反对(0) 摆脱菜鸟 | 园豆:16 (初学一级) | 2016-03-18 15:33
0

用 await 的调用产生异常不是AggregateException,而是你原始的异常,你捕获错异常类型了,用Exception或FormatException都能捕获到的。

Task中对于没有捕获的异常,像你这段代码中的,是不会导致程序终止的,用TaskScheduler.UnobservedTaskException可以查看到(要触发GC的时候才能有该事件)。

天方 | 园豆:5407 (大侠五级) | 2016-03-19 08:59
-1

将 public string GetString() 改为 async 方法:

public static async Task<string> GetString()
{
    Thread.Sleep(3000);
    int s = int.Parse("ab");//抛出异常
    return s.ToString();
}

将 catch (AggregateException ex) 改为 catch (Exception ex) 就能捕获到异常了。

dudu | 园豆:31075 (高人七级) | 2016-03-19 22:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册