using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using System.Threading;
using System.Collections.Concurrent;

namespace Sample3
{
    class Program
    {
        static void Main(string[] args)
        {
            //task.Cancel() 取消任务
            //task.Wait() 等待任务执行完成
            Sample1();
            Console.WriteLine("-------------------------");
            Sample2();
            Console.ReadLine();
        }


        static void Sample1() {
            var task1 = new Task(() =>
            {
                Console.WriteLine("任务1 Begin");
                System.Threading.Thread.Sleep(2000);
                Console.WriteLine("任务1 Finish");
            });
            var task2 = new Task(() =>
            {
                Console.WriteLine("任务2 Begin");
                System.Threading.Thread.Sleep(3000);
                Console.WriteLine("任务2 Finish");
            });
            task1.Start();
            task2.Start();
            /* Task.WaitAll, 等待所有的任务执行完成
             * Task.WaitAny,等待任何一个任务完成就继续向下执行
             */
            Task.WaitAll(task1, task2);
            Console.WriteLine("All task finished!");
        }

        static void Sample2() {
            var task1 = new Task(() =>
            {
                Console.WriteLine("任务1 Begin");
                System.Threading.Thread.Sleep(2000);
                Console.WriteLine("任务1 Finish");
            });
            var task2 = new Task(() =>
            {
                Console.WriteLine("任务2 Begin");
                System.Threading.Thread.Sleep(3000);
                Console.WriteLine("任务2 Finish");
            });
            task1.Start();
            task2.Start();
            //ContinueWith就是在第一个Task完成后自动启动下一个Task
            var result = task1.ContinueWith<string>(task =>
            {
                Console.WriteLine("task1 finished!");
                return "This is task result!";
            });
            //回调信息
            Console.WriteLine(result.Result.ToString());
        }
    }
}


本文转载:CSDN博客