任务Task、先后任务

Task类似后台线程。

using System;
using System.Threading;
using System.Threading.Tasks;//引用命名空间

namespace ConsoleApplication3
{
    class Program
    {
        void DownloadFile()
        {
            Console.WriteLine("任务开始" );
            Thread.Sleep(2000);
            Console.WriteLine("任务结束");
        }
        static void Main(string[] args)
        {
            Program p = new Program();//类的对象,方便引用非静态成员
            Task t = new Task(p.DownloadFile);//创建任务
            t.Start();
            //TaskFactory tf = new TaskFactory();//任务工厂,方便创建多个Task
            //Task t = tf.StartNew(p.DownloadFile);
            //Task t1 = tf.StartNew(p.DownloadFile);
            //Task t2 = tf.StartNew(p.DownloadFile);

            Console.ReadKey();
        }
    }
}

先后任务:一个任务依赖于另一个任务。即有先后顺序。使用ContinueWith

后继任务,方法参数不可省略,类似线程池

using System;
using System.Threading;
using System.Threading.Tasks;//引用命名空间

namespace ConsoleApplication3
{
    class Program
    {
        void DoFirst()
        {
            Console.WriteLine("任务1开始" );
            Thread.Sleep(2000);
        }
        void DoSecond(Task a)//后继任务,参数不可省略,类似线程池
        {
            Console.WriteLine("任务2开始");
            Thread.Sleep(2000);            
        }
        void DoThird(Task a)
        {
            Console.WriteLine("任务3开始");
            Thread.Sleep(2000);
        }
        static void Main(string[] args)
        {
            Program p = new Program();//类的对象,方便引用非静态成员
            Task t1 = new Task(p.DoFirst);//任务1
            Task t11 = t1.ContinueWith(p.DoSecond);//任务1结束后,异步执行后继任务2、3
            Task t12 = t1.ContinueWith(p.DoThird);
            Task t111 = t11.ContinueWith(p.DoSecond);//任务2结束后,才执行

            t1.Start();

            Console.ReadKey();
        }
    }
}

一个任务A中启动一个新任务B,两个任务异步执行,可认为同时执行。

using System;
using System.Threading;
using System.Threading.Tasks;//引用命名空间

namespace ConsoleApplication3
{
    class Program
    {        
        void DoFirst()//2s
        {
            Console.WriteLine("任务1开始");
            Task t2 = new Task(DoSecond);//任务1中启动了任务2
            t2.Start();//异步执行,可以认为1、2同时启动
            Thread.Sleep(2000);
            Console.WriteLine("任务1结束");
        }
        void DoSecond()//5s
        {
            Console.WriteLine("任务2开始");
            Thread.Sleep(5000);
            Console.WriteLine("任务2结束");
        }
        static void Main(string[] args)
        {
            Program p = new Program();//类的对象,方便调用成员
            Task t1 = new Task(p.DoFirst);//任务1启动          
            t1.Start();
            Console.ReadKey();
        }
    }
}

更深入内容参考:

https://blog.csdn.net/qq3401247010/article/details/81542461

https://blog.csdn.net/EthanWhite/article/details/52171262

原文地址:https://www.cnblogs.com/xixixing/p/10850552.html