简体   繁体   中英

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). 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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