开发者

Exception Handling (Task Parallel Library) .Net Framework 4.0 Beta 2

at the moment I am trying some of the new Features of the Task Parallel Library, shipped with the .Net Framework 4.0 Beta 2.

My question relates specifically to the Exception Handling within the TPL as described here: http://msdn.microsoft.com/en-us/library/dd997415%28VS.100%29.aspx

First example (changed it a little bit):

    static void Main(string[] args)
    {
        var task1 = Ta开发者_Python百科sk.Factory.StartNew(() =>
        {
            throw new Exception("I'm bad, but not too bad!"); // Unhandled Exception here...
        });

        try
        {
            task1.Wait(); // Exception is not handled here....
        }
        catch (AggregateException ae)
        {
            foreach (var e in ae.InnerExceptions)
            {
                Console.WriteLine(e.Message);
            }

        }

        Console.ReadLine();
    }

According to the documentation the Exception should be propagated back to the to the joining thread which calls: task1.Wait().

But I always get an Unhandled Exception within:

var task1 = Task.Factory.StartNew(() =>
{
    throw new MyCustomException("I'm bad, but not too bad!");
});

Could someone explain to me why, or does someone know if there something has changed since the release of Beta 2?


The answer is in the article you linked:

When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue and see the exception-handling behavior that is demonstrated in these examples. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.


Your exception is probably being thrown before you ever reach the try statement, and the corresponding wait.

Try this:

static void Main(string[] args)
{

    try
    {   
        // Move this inside teh try block, so catch can catch any exceptions thrown before you get to task1.Wait();
        var task1 = Task.Factory.StartNew(() =>
        {
            throw new Exception("I'm bad, but not too bad!"); // Unhandled Exception here...
        });

        task1.Wait(); // Exception is not handled here....
    }
    catch (AggregateException ae)
    {
        foreach (var e in ae.InnerExceptions)
        {
            Console.WriteLine(e.Message);
        }

    }

    Console.ReadLine();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜