简体   繁体   English

没有捕获TaskEx.Run的任务引发的异常

[英]Not catching exception thrown by TaskEx.Run's task

I'm having trouble with the async CTP, trying to figure out what the correct way to handle exceptions is. 我在使用异步CTP时遇到了麻烦,试图弄清楚处理异常的正确方法是什么。 The code below crashes my program, when as far as I can tell, the await should be catching and rethrowing the exception in the context it is called from, so the Not caught! 下面的代码使我的程序崩溃,据我所知, await应该在从其调用的上下文中捕获并重新抛出异常,因此Not caught! block should catch the exception. 块应该捕获异常。

try {
  await TaskEx.Run(() => {
    throw new Exception();
  });
} catch {
  // Not caught!
}

Thanks for any help or suggestions. 感谢您的帮助或建议。

Works fine for me using the beta (rather than the CTP, hence the TaskEx becoming Task ): 使用beta对我来说很好用(而不是CTP,因此TaskEx成为Task ):

using System;
using System.Threading.Tasks;

class Test
{
    static void Main()
    {
        Task t = Foo();
        t.Wait();
    }

    static async Task Foo()
    {
        try
        {
            await Task.Run(() => { throw new Exception(); });
        }
        catch (Exception e)
        {
            Console.WriteLine("Bang! " + e);
        }
    }

Output: 输出:

Bang! System.Exception: Exception of type 'System.Exception' was thrown.
   at Test.<Foo>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter
            .HandleNonSuccessAndDebuggerNotification(Task task)
   at Test.<Foo>d__2.MoveNext()

What does the same code do on your machine? 相同的代码在您的计算机上做什么?

Pro Tip: Visual Studio is telling you that the exception is unhandled, but if you F5 through, you will see that it does get caught. 专家提示:Visual Studio 告诉您未处理该异常,但是如果您按F5键,则会看到确实捕获了该异常。

(This from comments on Jon's answer, but I think it deserves its own answer) (摘自对乔恩的回答的评论,但我认为这值得自己回答)

A little bit of rearranging should work: 进行一些重新排列应该可以:

  await TaskEx.Run(() => {
    try {
      throw new Exception();
    } catch {
      // Caught!
    }
  });

EDIT: 编辑:

I get the same results as Jon Skeet due to the fact that I'm also running the VS11 beta. 由于我也正在运行VS11 beta,因此获得与Jon Skeet相同的结果。 I cannot speak for the CTP. 我不能代表CTP。

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

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