4

次の単純化されたコードが与えられた場合

    /// <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);
    }

たとえば、

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

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

VS2010 デバッガーで実行しているときに、非常に厄介な問題が発生しました。「概要」の状態と同様に、デバッガーは、例外をキャッチしなかったと信じて「tOpen」タスクのスローで中断します (これは「さらに下で行います」)。 " 'tComplete' タスク内)。デバッグ セッションを続行した場合にのみ、例外が「バブルアップ」され、必要に応じて処理されることがわかります。このメソッドが定期的な時間間隔で実行された場合 (実際にそうです!)、デバッガーが各間隔で中断するため、デバッグは悪夢になります。

コンソールでプログラムを実行しても、この動作は発生しません。

  1. なぜデバッガがこの行で壊れるのか、誰かが私に説明できますか、つまり、表示されません
  2. そのようなコードが存在する VS2010 内でコードを合理的にデバッグできるオプションは何ですか?
4

1 に答える 1