从Task.ContinueWith传播异常?

时间:2017-12-07 12:42:17

标签: c# exception-handling task

在以下程序中,如何将OverflowException传播到Main?

class Program
{
    static readonly CancellationTokenSource Source = new CancellationTokenSource();
    static void Main(string[] args)
    {
        CallDoSomething(1);

        Console.WriteLine("Press enter to exit");
        Console.ReadLine();
    }

    static void CallDoSomething(int foo)
    {
        var task = Task.Factory.StartNew(() => DoSomething(foo), Source.Token);
        task.ContinueWith(t =>
        {
            var result = task.Result;
            Console.WriteLine(result);

            Thread.Sleep(500);

            CallDoSomething(result);
        }, TaskContinuationOptions.NotOnCanceled);

        task.ContinueWith(t => t.Exception?.Handle(ex => throw ex), TaskContinuationOptions.OnlyOnFaulted);
    }

    static int DoSomething(int foo)
    {
        if (foo > 100)
        {
            Source.Cancel();
            throw new OverflowException("foo overflowed");
        }

        return foo * 2;
    }
}

0 个答案:

没有答案