C# 5.0 Task中实现异常抛出

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ExceptionsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Task task;
            try
            {
                task = Task.Run(() => TaskMethod("task 1", 2));
                //Thread.Sleep(TimeSpan.FromSeconds(3));
                //task.Wait();
                int result = task.Result;
                Console.WriteLine("result: {0}", result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("exception caught: {0}", ex);
            }

            Console.WriteLine("------------------------------");
            Console.WriteLine();

            try
            {
                task = Task.Run(() => TaskMethod("task 2", 2));
                //用此种方式来获取任务的返回值,如果有的话
                int result = task.GetAwaiter().GetResult();
                Console.WriteLine("result: {0}", result);
            }
            catch (Exception ex)
            {
                //异常信息将与task1中不同
                Console.WriteLine("exception caught: {0}", ex);
            }


            Console.WriteLine("------------------------------");
            Console.WriteLine();

            var t1 = new Task(() => TaskMethod("task 3", 3));
            var t2 = new Task(() => TaskMethod("task 4", 2));
            var complexTask = Task.WhenAll(t1, t2);
            var exceptionHandler = complexTask.ContinueWith(t =>
            Console.WriteLine("exception caught: {0}", t.Exception),
            //仅当任务失败时才做的事
            TaskContinuationOptions.OnlyOnFaulted);

            t1.Start();
            t2.Start();

            Console.ReadKey();
        }

        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on a thread is {1}. is thread pool thread {2}",
                name,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            //出现运行异常时
            //尝试修改 ‘工具’‘选项’‘调试’‘常规’将【启用仅我的代码】去除勾选
            throw new Exception("Boom!");
            return 42 * seconds;
        }
    }
}

你可能感兴趣的:(c#,task)