简体   繁体   English

捕获产生内部任务的任务的异常

[英]Catching Exceptions of a Task that spawns an inner task

Given the following simplified code 给出以下简化代码

    /// <summary>
    /// Within the VS2010 debugger, the following test will cease with an 
    /// "Exception was unhandled by user code". 
    /// (Debug window reports a "A first chance exception of type 
    /// 'System.Exception' ..." BEFORE the exception is caught 
    /// further down in the execution path.)
    /// OUTSIDE the VS2010 debugger, the exception is caught by the tComplete 
    /// task that follows the tOpen task, just as expected.
    /// </summary>
    public void StartToOpen_Simple()
    {
        Task tOpen = Task.Factory.StartNew(() => {
            //do some work before spawning another task here
            try
            {
                return Task.Factory.StartNew(() => {
                    Thread.Sleep(2000);
                    //First chance exception occurs here:
                    throw new Exception("Some generic exception");
                }, TaskCreationOptions.AttachedToParent);
            } catch (Exception ex)
            {
                //never fires
                var source = new TaskCompletionSource<object>();
                source.TrySetException(ex);
                return source.Task;
            }
        }).Unwrap();

        Task tComplete = tOpen.ContinueWith(t => {
            if (t.Exception != null)
            {
                Exception LastOpenException = t.Exception.Flatten().GetBaseException();
                if (LastOpenException is OperationCanceledException)
                {
                    Console.WriteLine("OperationCanceledEx: " + LastOpenException.Message);
                } else
                {
                    Console.WriteLine("Some exception occured in the tOpen task, but we're prepared for it here in the tComplete task.");
                    Console.WriteLine("The exception message was: {0}", LastOpenException.Message);
                }
            } else
            {
                //do something if no exception occured (doesn't happen in this example)
            }
        }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.AttachedToParent, TaskScheduler.Default);
    }

and testing it for example via 并测试它,例如通过

    static void Main(string[] args)
    {
        AsyncTest test = new AsyncTest();
        test.StartToOpen_Simple();

        Console.WriteLine("Started async task. Waiting for exception");
        Console.ReadKey();
    }

I observe a very annoying issue while running it in the VS2010 debugger: Just like the "Summary" states, the debugger breaks at the throw in the 'tOpen' task believing that I didn't catch the exception (which i do "further below" in the 'tComplete' task). 我在VS2010调试器中运行时遇到一个非常烦人的问题:就像“摘要”状态一样,调试器在'tOpen'任务中抛出,相信我没有捕获异常(我在下面进一步说明) “在'tComplete'任务中)。 Only if I continue the debugging session do I see that the exception is "bubbled up" and hence handled as desired. 只有当我继续调试会话时,才会看到异常“冒泡”并因此按需处理。 If this method were run on a regular time interval (which it is!) debugging this becomes a nightmare, because the debugger breaks on each interval. 如果这个方法是在一个固定的时间间隔(它是!)上运行的,那么调试就变成了一场噩梦,因为调试器会在每个时间间隔内中断。

Running the program on a console, doesn't exhibit this behavior. 在控制台上运行该程序,不会出现此行为。

  1. Can someone explain to me why the Debugger breaks at this line, ie it doesn't see 有人可以向我解释为什么调试器在这一行中断,即它没有看到
  2. What are my options of being able to reasonably debug code inside VS2010 where such code exists? 有哪些能够合理调试VS2010中存在此类代码的代码?

First chance exception messages most often do not mean there is a problem in the code. 第一次机会异常消息通常并不意味着代码中存在问题。 For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled. 对于优雅处理异常的应用程序/组件,第一次机会异常消息让开发人员知道遇到并处理了异常情况。

Please refer this 请参考这个

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

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