1、Task的优势
  ThreadPool比较Thread来说具有了累累优势,不过ThreadPool却又存在部分使用上的不便利。比如:
  ◆ ThreadPool不支持线程的打消、完毕、退步布告等交互性操作;
  ◆ ThreadPool不协理线程执行的主次顺序;
  以往,假如开发者要贯彻上述效率,须求形成很多附加的干活,今后,FCL中提供了叁个作用更强有力的定义:Task。Task在线程池的功底上举行了优化,并提供了更加多的API。在FCL4.0中,固然大家要编写多线程程序,Task显著已经优化守旧的主意。
  以下是三个简约的天职示例:

 

Task和ThreadPool的作用类似,能够用来创立1些轻量级的并行职责。对于将2个职责放进线程池
    ThreadPool.QueueUserWorkItem(A);

聊起异步,Thread,Task,async/await,IAsyncResult
那几个事物必定是绕不开的,今日就来挨家挨户聊聊他们

金沙注册送58 1金沙注册送58 2

Task.Waitall阻塞了当下线程直到全完。whenall开启个新监察和控制线程去判读括号里的享有线程执市场价格况并随即回去,等都成功了就淡出监察和控制线程并回到监察和控制数据。

那段代码用Task来兑现的话,格局如下:     Task.Factory.StartNew(A);

 

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task t = new Task(() =>
            {
                Console.WriteLine("任务开始工作……");
                //模拟工作过程
                Thread.Sleep(5000);
            });
            t.Start();
            t.ContinueWith((task) =>
            {
                Console.WriteLine("任务完成,完成时候的状态为:");
                Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
            });
            Console.ReadKey();
        }
    }
}

task.Result会等待异步方法再次回到,当然阻塞住了。别和await 同时用。

那两端代码的应用和促成的效果都十一分相似。但和TheadPool比较,Task有着越多的效能,越发有利我们应用。

1.线程(Thread)

Program

Task和ThreadPool的法力类似,能够用来创制一些轻量级的并行任务。对于将3个职责放进线程池
的那个事儿,0并行库介绍。    ThreadPool.QueueUserWorkItem(A);

固然大家要创建四个任务,并等待它们形成。那些效能用TheadPool完毕如下:

 

 

那段代码用Task来贯彻的话,格局如下:
    Task.Factory.StartNew(A);

    using (ManualResetEvent mre1 = new ManualResetEvent(false))     using (ManualResetEvent mre2 = new ManualResetEvent(false))     using (ManualResetEvent mre3 = new ManualResetEvent(false))     {         ThreadPool.QueueUserWorkItem(delegate         {             A();
            mre1.Set();         });         ThreadPool.QueueUserWorkItem(delegate         {             B();
            mre2.Set();         });         ThreadPool.QueueUserWorkItem(delegate         {             C();
            mre3.Set();         });         WaitHandle.WaitAll(new WaitHandle[] { mre1, mre2, mre3 });
    }

二十多线程的意义在于2个应用程序中,有多少个实施部分能够同时推行;对于比较耗费时间的操作(例如io,数据库操作),恐怕等待响应(如WCF通讯)的操作,能够独自开启后台线程来执行,那样主线程就不会堵塞,能够继承往下实施;等到后台线程执行实现,再文告主线程,然后做出相应操作!

2、Task的用法
  贰.1、创设职责
  无重临值的方法
  方式1:
  var t1 = new Task(() => TaskMethod(“Task 1”));
  t1.Start();
  Task.WaitAll(t一);//等待全体任务实现
  注:
  职务的动静:
  Start之前为:Created
  Start之后为:WaitingToRun

那两端代码的采纳和贯彻的机能都十二分相似。但和TheadPool比较,Task有着越来越多的功能,特别有益于大家采纳。

用Task类完成起来就相对简单多了:

 

  方式2:
  Task.Run(() => TaskMethod(“Task 2”));

设若大家要开创四个职责,并听候它们形成。这些功效能TheadPool实现如下:

    Task t1 = Task.Factory.StartNew(delegate { A(); });     Task t2 = Task.Factory.StartNew(delegate { B(); });     Task t3 = Task.Factory.StartNew(delegate { C(); });     t1.Wait();
    t2.Wait();     t3.Wait();

在C#中打开新线程比较简单

  方式3:
  Task.Factory.StartNew(() => TaskMethod(“Task 叁”));
直接异步的法子
  或者
  var t3=Task.Factory.StartNew(() => TaskMethod(“Task 3”));
  Task.WaitAll(t三);//等待全数职责完结
  注:
  职分的意况:
  Start之前为:Running
  Start之后为:Running

    using (ManualResetEvent mre1 = new ManualResetEvent(false))
    using (ManualResetEvent mre2 = new ManualResetEvent(false))
    using (ManualResetEvent mre3 = new ManualResetEvent(false))
    {
        ThreadPool.QueueUserWorkItem(delegate
        {
            A();
            mre1.Set();
        });
        ThreadPool.QueueUserWorkItem(delegate
        {
            B();
            mre2.Set();
        });
        ThreadPool.QueueUserWorkItem(delegate
        {
            C();
            mre3.Set();
        });
        WaitHandle.WaitAll(new WaitHandle[] { mre1, mre2, mre3 });
    }

大概我们还足以如此写:

 

金沙注册送58 3金沙注册送58 4

用Task类达成起来就相对简便易行多了:

    Task t1 = Task.Factory.StartNew(delegate { A(); });     Task t2 = Task.Factory.StartNew(delegate { B(); });     Task t3 = Task.Factory.StartNew(delegate { C(); });     Task.WaitAll(t1, t2, t3);

static void Main(string[] args)

{

    Console.WriteLine(“主线程发轫”);

    //IsBackground=true,将其安装为后台线程

    Thread t = new Thread(Run) { IsBackground = true };

    t.Start();

   Console.WriteLine(“主线程在做别的的事!”);

    //主线程结束,后台线程会自动终止,不管有没有实施到位

    //Thread.Sleep(300);

    Thread.Sleep(1500);

    Console.WriteLine(“主线程甘休”);

}

static void Run()

{

    Thread.Sleep(700);

    Console.WriteLine(“那是后台线程调用”);

}

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var t1 = new Task(() => TaskMethod("Task 1"));
            var t2 = new Task(() => TaskMethod("Task 2"));
            t2.Start();
            t1.Start();
            Task.WaitAll(t1, t2);
            Task.Run(() => TaskMethod("Task 3"));
            Task.Factory.StartNew(() => TaskMethod("Task 4"));
            //标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。
            Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);

            #region 常规的使用方式
            Console.WriteLine("主线程执行业务处理.");
            //创建任务
            Task task = new Task(() =>
            {
                Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(i);
                }
            });
            //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
            task.Start();
            Console.WriteLine("主线程执行其他处理");
            task.Wait();
            #endregion

            Thread.Sleep(TimeSpan.FromSeconds(1));
            Console.ReadLine();
        }

        static void TaskMethod(string name)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
        }
    }
}

    Task t1 = Task.Factory.StartNew(delegate { A(); });
    Task t2 = Task.Factory.StartNew(delegate { B(); });
    Task t3 = Task.Factory.StartNew(delegate { C(); });
    t1.Wait();
    t2.Wait();
    t3.Wait(); 

上边大家来大约的介绍一下Task的基本用法:

 

Program

抑或我们还足以如此写:

创建Task

创制Task有三种格局

  1. 经过构造函数成立 Task t1 = new Task(A);
  2. 通过TaskFactory创建 Task t1 = Task.Factory.StartNew(A);

那三种艺术实际上是同一的,第三种形式之中也不胫而走了暗中同意的TaskFactory——Task.Factory。TaskFactory起着对Task进行创办和调度管理的效果,类似于在此之前CTP版中的TaskManager,关于这些目的,后续会独自写一篇文章介绍。

实践结果如下图

  async/await的落到实处格局:

    Task t1 = Task.Factory.StartNew(delegate { A(); });
    Task t2 = Task.Factory.StartNew(delegate { B(); });
    Task t3 = Task.Factory.StartNew(delegate { C(); });
    Task.WaitAll(t1, t2, t3);

初阶运转Task

在上述二种制造Task格局中,方式1创建的Task并不曾即时施行,须要手动调用t一.Start()来实施(类似于线程,必要手动执行)。而艺术二成立的Task是即时执行的(类似于线程池,是电动执行的),从那二种艺术的函数名称也足以看看那或多或少。

 

金沙注册送58 5金沙注册送58 6

上面大家来不难的牵线一下Task的基本用法:

等待Task完成

等候Task达成的也有三种:

  1. 调用Task的积极分子函数t.Wait()。
  2. 调用Task的静态函数Task.WaitAll()或Task.WaitAny()。

那三种办法和.net中常用的WaitHandle大概,那里就不多介绍了。

金沙注册送58 7

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

namespace ConsoleApp1
{
    class Program
    {
        async static void AsyncFunction()
        {
            await Task.Delay(1);
            Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(string.Format("AsyncFunction:i={0}", i));
            }
        }

        public static void Main()
        {
            Console.WriteLine("主线程执行业务处理.");
            AsyncFunction();
            Console.WriteLine("主线程执行其他处理");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(string.Format("Main:i={0}", i));
            }
            Console.ReadLine();
        }
    }
}

创建Task

开创Task有两种办法

  1. 透过构造函数创立
    Task t1 = new Task(A);
  2. 通过TaskFactory创建
    Task t1 = Task.Factory.StartNew(A);

那二种艺术实际是如出1辙的,第二种情势之中也传出了暗中同意的TaskFactory——Task.Factory。TaskFactory起着对Task实行创办和调度管理的功用,类似于在此在此以前CTP版中的TaskManager,关于那些指标,后续会独自写1篇小说介绍。

取消Task

撤销Task的秘诀较CTP的时候复杂和强大了成千成万,后续加一个单独的稿子单独介绍。

 

Program

先导运营Task

在上述二种成立Task格局中,方式一创设的Task并不曾当即施行,供给手动调用t一.Start()来进行(类似于线程,供给手动执行)。而艺术2创立的Task是当时施行的(类似于线程池,是自动执行的),从那三种方法的函数名称也能够看出那或多或少。

尤其处理

当Task在执行进度中生出尤其时,该特别会在Wait或WaitAll等函数中再度throw。能够经过Task的Exception属性来赢得产生的13分。

    var t1 = Task.Factory.StartNew(() => { throw new
Exception(“t1 error occor”); });     var t2 = Task.Factory.StartNew(() => { throw new
Exception(“t2 error occor”); });
    try     {         Task.WaitAll(t1, t2);     }     catch (Exception)     {         Console.WriteLine(t1.Exception.InnerException.Message);
        Console.WriteLine(t2.Exception.InnerException.Message);
    }

能够观察在开发银行后台线程之后,主线程继续往下举行了,并不曾等到后台线程执行完之后。

  带重回值的点子
  方式4:
  Task<int> task = CreateTask(“Task 1”);
  task.Start();
  int result = task.Result;

等待Task完成

伺机Task完毕的也有三种:

  1. 调用Task的积极分子函数t.Wait()。
  2. 调用Task的静态函数Task.WaitAll()或Task.WaitAny()。

那二种艺术和.net中常用的WaitHandle大概,那里就不多介绍了。

取得Task的再次回到值

在CTP版本中,是经过Fucture<>类来获取带再次回到值的Task的,未来早已将类改名称叫Task<>了,从而实现命名情势的统一。使用方式大约同一,正是多了3个Result属性,能够在Task执行到位后获取再次回到值。示例如下:

    var t1 = Task.Factory.StartNew(() => 3);     t1.Wait();     Console.WriteLine(t1.Result);

 

金沙注册送58 8金沙注册送58 9

取消Task

撤除Task的秘籍较CTP的时候复杂和强大了过多,后续加二个独自的小说单独介绍。

其它

在Task中还有好多老大有效的职责调度和错误处理等的方法和性质,它们使得并发操作变得特别有力和省略,今后会陆续介绍这个文化。

1.1 线程池

 

试想一下,固然有恢宏的职分需求处理,例如网址后台对于HTTP请求的处理,那是否要对每二个伸手创制2个后台线程呢?显明不合适,这会占有大量内部存款和储蓄器,而且数十次地创立的历程也会严重影响速度,那咋做吧?

 

线程池就是为了消除那一题材,把创造的线程存起来,形成一个线程池(里面有七个线程),当要处理义务时,若线程池中有闲暇线程(前贰个任务履行到位后,线程不会被回收,会棉被服装置为空闲状态),则直接调用线程池中的线程执行(例asp.net处理体制中的Application对象),使用事例:

 

for (int i = 0; i < 10; i++)

{

    ThreadPool.QueueUserWorkItem(m =>

    {

       
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());

    });

}

Console.Read();

 

运营结果:

 

金沙注册送58 10

 

可以看出,纵然举办了拾2遍,但并未有创制13个线程。

 

1.2 信号量(Semaphore)

 

Semaphore负责协调线程,能够界定对某1能源访问的线程数量,那里对SemaphoreSlim类的用法做一个简短的例证:

 

static SemaphoreSlim semLim = new SemaphoreSlim(3);
//3表示最多只可以有八个线程同时做客

static void Main(string[] args)

{

    for (int i = 0; i < 10; i++)

    {

        new Thread(SemaphoreTest).Start();

    }

    Console.Read();

}

static void SemaphoreTest()

{

    semLim.Wait();

    Console.WriteLine(“线程” +
Thread.CurrentThread.ManagedThreadId.ToString() + “伊始履行”);

    Thread.Sleep(2000);

    Console.WriteLine(“线程” +
Thread.CurrentThread.ManagedThreadId.ToString() + “执行完成”);

    semLim.Release();

}

金沙注册送58 , 

进行理并了结果如下:

 

金沙注册送58 11

 

金沙注册送58 12

 

能够看到,刚伊始唯有七个线程在推行,当一个线程执行达成并释放之后,才会有新的线程来推行办法!

 

除开SemaphoreSlim类,还能利用Semaphore类,感觉越是灵敏,感兴趣的话能够搜一下,那里就不做示范了!

 

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

namespace ConsoleApp1
{
    class Program
    {
        static Task<int> CreateTask(string name)
        {
            return new Task<int>(() => TaskMethod(name));
        }

        static void Main(string[] args)
        {
            TaskMethod("Main Thread Task");
            Task<int> task = CreateTask("Task 1");
            task.Start();
            int result = task.Result;
            Console.WriteLine("Task 1 Result is: {0}", result);

            task = CreateTask("Task 2");
            //该任务会运行在主线程中
            task.RunSynchronously();
            result = task.Result;
            Console.WriteLine("Task 2 Result is: {0}", result);

            task = CreateTask("Task 3");
            Console.WriteLine(task.Status);
            task.Start();

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }

            Console.WriteLine(task.Status);
            result = task.Result;
            Console.WriteLine("Task 3 Result is: {0}", result);

            #region 常规使用方式
            //创建任务
            Task<int> getsumtask = new Task<int>(() => Getsum());
            //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
            getsumtask.Start();
            Console.WriteLine("主线程执行其他处理");
            //等待任务的完成执行过程。
            getsumtask.Wait();
            //获得任务的执行结果
            Console.WriteLine("任务执行结果:{0}", getsumtask.Result.ToString());
            #endregion
        }

        static int TaskMethod(string name)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            return 42;
        }

        static int Getsum()
        {
            int sum = 0;
            Console.WriteLine("使用Task执行异步操作.");
            for (int i = 0; i < 100; i++)
            {
                sum += i;
            }
            return sum;
        }
    }
}

不行处理

当Task在推行进度中产生尤其时,该尤其会在Wait或WaitAll等函数中重新throw。可以因而Task的Exception属性来获取爆发的不行。

    var t1 = Task.Factory.StartNew(() => { throw new Exception(“t1
error occor”); });
    var t2 = Task.Factory.StartNew(() => { throw new Exception(“t2
error occor”); });

    try
    {
        Task.WaitAll(t1, t2);
    }
    catch (Exception)
    {
        Console.WriteLine(t1.Exception.InnerException.Message);
        Console.WriteLine(t2.Exception.InnerException.Message);
    }

2.Task

 

Task是.NET4.0进入的,跟线程池ThreadPool的效能看似,用Task开启新任务时,会从线程池中调用线程,而Thread每回实例化都会成立1个新的线程。

 

Console.WriteLine(“主线程运营”);

//Task.Run运维贰个线程

//Task运转的是后台线程,要在主线程中等待后台线程执行完结,能够调用Wait方法

//Task task = Task.Factory.StartNew(() => { Thread.Sleep(1500);
Console.WriteLine(“task启动”); });

Task task = Task.Run(() => { 

    Thread.Sleep(1500);

    Console.WriteLine(“task启动”);

});

Thread.Sleep(300);

task.Wait();

Console.WriteLine(“主线程甘休”);

 

履行结果如下:

 

金沙注册送58 13

 

敞开新任务的点子:Task.Run()或然Task.Factory.StartNew(),开启的是后台线程要在主线程中等待后台线程执行实现,能够行使Wait方法(会以协同的章程来进行)。不用Wait则会以异步的措施来推行。

 

正如一下Task和Thread:

 

static void Main(string[] args)

{

    for (int i = 0; i < 5; i++)

    {

        new Thread(Run1).Start();

    }

    for (int i = 0; i < 5; i++)

    {

        Task.Run(() => { Run2(); });

    }

}

static void Run1()

{

    Console.WriteLine(“Thread Id =” +
Thread.CurrentThread.ManagedThreadId);

}

static void Run2()

{

    Console.WriteLine(“Task调用的Thread Id =” +
Thread.CurrentThread.ManagedThreadId);

}

 

推行结果:

 

金沙注册送58 14

 

可以看出来,直接用Thread会开启多个线程,用Task(用了线程池)开启了2个!

 

Program

收获Task的再次回到值

在CTP版本中,是经过Fucture<>类来获取带重返值的Task的,今后曾经将类改名称叫Task<>了,从而完结命名格局的合并。使用方法差不离相同,正是多了三个Result属性,能够在Task执行到位后获得重回值。示例如下:

    var t1 = Task.Factory.StartNew(() => 3);
    t1.Wait();
    Console.WriteLine(t1.Result);

 

 

2.1 Task<TResult>

 

Task<TResult>正是有再次回到值的Task,TResult正是回去值类型。

 

Console.WriteLine(“主线程初始”);

//重回值类型为string

Task<string> task = Task<string>.Run(() => {

    Thread.Sleep(2000); 

    return Thread.CurrentThread.ManagedThreadId.ToString(); 

});

//会等到task执行完成才会输出;

Console.WriteLine(task.Result);

Console.WriteLine(“主线程甘休”);

 

运营结果:

 

金沙注册送58 15

 

因此task.Result可以取到再次回到值,若取值的时候,后台线程还没执行完,则会等待其履行实现!

 

简单提一下:

 

Task任务能够经过CancellationTokenSource类来撤除,感觉用得不多,用法相比简单,感兴趣的话可以搜一下!

 

    async/await的实现:

3. async/await

 

async/await是C#伍.0中推出的,先上用法:

 

static void Main(string[] args)

{

    Console.WriteLine(“——-主线程运转——-“);

    Task<int> task = GetStrLengthAsync();

    Console.WriteLine(“主线程继续执行”);

    Console.WriteLine(“Task重返的值” + task.Result);

    Console.WriteLine(“——-主线程甘休——-“);

}

static async Task<int> GetStrLengthAsync()

{

    Console.WriteLine(“GetStrLengthAsync方法初步实践”);

    //此处重回的<string>中的字符串类型,而不是Task<string>

    string str = await GetString();

    Console.WriteLine(“GetStrLengthAsync方法执行完成”);

    return str.Length;

}

static Task<string> GetString()

{

   //Console.WriteLine(“GetString方法早先推行”)

    return Task<string>.Run(() =>

    {

        Thread.Sleep(2000);

        return “GetString的再次来到值”;

    });

}

 

async用来修饰方法,注解那个方法是异步的,注脚的秘籍的归来类型必须为:void,Task或Task<TResult>。

 

await必须用来修饰Task或Task<TResult>,而且不得不现身在已经用async关键字修饰的异步方法中。平时意况下,async/await成对出现才有含义,看看运转结果:

 

金沙注册送58 16

 

能够看出来,main函数调用GetStrLengthAsync方法后,在await在此以前,都以联合署名施行的,直到遇见await关键字,main函数才回到继续执行。

 

那么是还是不是是在遇见await关键字的时候程序自动开启了1个后台线程去履行GetString方法呢?

 

前几日把GetString方法中的那行注释加上,运转的结果是:

 

金沙注册送58 17

 

大家可以见到,在遇见await关键字后,未有继续执行GetStrLengthAsync方法后边的操作,也并未立即反回到main函数中,而是进行了GetString的率先行,以此能够断定await那里并从未开启新的线程去执行GetString方法,而是以四只的诀窍让GetString方法执行,等到执行到GetString方法中的Task<string>.Run()的时候才由Task开启了后台线程!

 

那么await的效劳是哪些呢?

 

能够从字面上驾驭,上面提到task.wait能够让主线程等待后台线程执行实现,await和wait类似,同样是等待,等待Task<string>.Run()开首的后台线程执行完结,区别的是await不会阻塞主线程,只会让GetStrLengthAsync方法暂停实施。

 

那正是说await是怎么形成的呢?有未有打开新线程去等待?

 

金沙注册送58 18

 

唯有五个线程(主线程和Task开启的线程)!至于怎么完毕的(作者也不知道……>_<),大家有趣味的话钻探下呢!

 

金沙注册送58 19金沙注册送58 20

4.IAsyncResult

 

IAsyncResult自.NET一.壹起就有了,包括可异步操作的办法的类须要贯彻它,Task类就兑现了该接口

 

 

金沙注册送58 21

 

在不依靠Task的景观下怎么落到实处异步呢?

 

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine(“主程序起首——————–“);

        int threadId;

        AsyncDemo ad = new AsyncDemo();

        AsyncMethodCaller caller = new
AsyncMethodCaller(ad.TestMethod);

 

        IAsyncResult result = caller.BeginInvoke(3000,out threadId,
null, null);

        Thread.Sleep(0);

        Console.WriteLine(“主线程线程 {0}
正在运营.”,Thread.CurrentThread.ManagedThreadId)

        //会阻塞线程,直到后台线程执行完结之后,才会往下实施

        result.AsyncWaitHandle.WaitOne();

        Console.WriteLine(“主程序在做一些工作!!!”);

        //获取异步执行的结果

        string returnValue = caller.EndInvoke(out threadId, result);

        //释放资源

        result.AsyncWaitHandle.Close();

        Console.WriteLine(“主程序甘休——————–“);

        Console.Read();

    }

}

public class AsyncDemo

{

    //供后台线程执行的措施

    public string TestMethod(int callDuration, out int threadId)

    {

        Console.WriteLine(“测试方法初阶执行.”);

        Thread.Sleep(callDuration);

        threadId = Thread.CurrentThread.ManagedThreadId;

        return String.Format(“测试方法执行的时刻 {0}.”,
callDuration.ToString());

    }

}

public delegate string AsyncMethodCaller(int callDuration, out int
threadId);

 

关键步骤正是新民主主义革命字体的片段,运营结果:

 

金沙注册送58 22

 

和Task的用法差距不是一点都不小!result.AsyncWaitHandle.WaitOne()就如Task的Wait。

 

5.Parallel

 

最终说一下在循环中打开拾贰线程的简单方法:

 

Stopwatch watch1 = new Stopwatch();

watch1.Start();

for (int i = 1; i <= 10; i++)

{

    Console.Write(i + “,”);

    Thread.Sleep(1000);

}

watch1.Stop();

Console.WriteLine(watch1.Elapsed);

Stopwatch watch2 = new Stopwatch();

watch2.Start();

//会调用线程池中的线程

Parallel.For(1, 11, i =>

{

    Console.WriteLine(i + “,线程ID:” +
Thread.CurrentThread.ManagedThreadId);

    Thread.Sleep(1000);

});

watch2.Stop();

Console.WriteLine(watch2.Elapsed);

 

运营结果:

 

金沙注册送58 23

 

循环List<T>:

 

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 6, 7,
8, 9 };

Parallel.ForEach<int>(list, n =>

{

    Console.WriteLine(n);

    Thread.Sleep(1000);

});

 

执行Action[]数组里面包车型的士章程:

 

Action[] actions = new Action[] { 

   new Action(()=>{

       Console.WriteLine(“方法1”);

   }),

    new Action(()=>{

       Console.WriteLine(“方法2”);

   })

};

Parallel.Invoke(actions);

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main()
        {
            var ret1 = AsyncGetsum();
            Console.WriteLine("主线程执行其他处理");
            for (int i = 1; i <= 3; i++)
                Console.WriteLine("Call Main()");
            int result = ret1.Result;                  //阻塞主线程
            Console.WriteLine("任务执行结果:{0}", result);
        }

        async static Task<int> AsyncGetsum()
        {
            await Task.Delay(1);
            int sum = 0;
            Console.WriteLine("使用Task执行异步操作.");
            for (int i = 0; i < 100; i++)
            {
                sum += i;
            }
            return sum;
        }
    }
}

 

Program

陆.异步的回调

 

为了简洁(偷懒),文中全体Task<TResult>的重临值都以平素用task.result获取,那样只要后台职分未有实行实现的话,主线程会等待其执行实现。那样的话就和一道1样了,壹般情状下不会如此用。不难演示一下Task回调函数的施用:

 

Console.WriteLine(“主线程开首”);

Task<string> task = Task<string>.Run(() => {

    Thread.Sleep(2000); 

    return Thread.CurrentThread.ManagedThreadId.ToString(); 

});

//会等到义务执行完以后执行

task.GetAwaiter().OnCompleted(() =>

{

    Console.WriteLine(task.Result);

});

Console.WriteLine(“主线程甘休”);

Console.Read();

 

举行理并了结果:

 

金沙注册送58 24

 

OnCompleted中的代码会在任务履行到位以往执行!

 

除此以外task.ContinueWith()也是1个重中之重的方法:

 

Console.WriteLine(“主线程开端”);

Task<string> task = Task<string>.Run(() => {

    Thread.Sleep(2000); 

    return Thread.CurrentThread.ManagedThreadId.ToString(); 

});

task.GetAwaiter().OnCompleted(() =>

{

    Console.WriteLine(task.Result);

});

task.ContinueWith(m=>{Console.WriteLine(“第七个义务达成啦!笔者是第1个职分”);});

Console.WriteLine(“主线程停止”);

Console.Read();

 

执行结果:

 

金沙注册送58 25

 

ContinueWith()方法能够让该后台线程继续执行新的职责。

 

Task的施用恐怕比较灵敏的,大家能够切磋下,好了,以上便是全体内容了,篇幅和能力都不难,希望对我们有用!

  贰.二、组合职责.孔蒂nueWith
   简单Demo:

金沙注册送58 26金沙注册送58 27

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main()
        {
            //创建一个任务
            Task<int> task = new Task<int>(() =>
            {
                int sum = 0;
                Console.WriteLine("使用Task执行异步操作.");
                for (int i = 0; i < 100; i++)
                {
                    sum += i;
                }
                return sum;
            });
            //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
            task.Start();
            Console.WriteLine("主线程执行其他处理");
            //任务完成时执行处理。
            Task cwt = task.ContinueWith(t =>
            {
                Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString());
            });
            task.Wait();
            cwt.Wait();
        }
    }
}

Program

   职务的串行:

金沙注册送58 28金沙注册送58 29

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcurrentStack<int> stack = new ConcurrentStack<int>();

            //t1先串行
            var t1 = Task.Factory.StartNew(() =>
            {
                stack.Push(1);
                stack.Push(2);
            });

            //t2,t3并行执行
            var t2 = t1.ContinueWith(t =>
            {
                int result;
                stack.TryPop(out result);
                Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
            });

            //t2,t3并行执行
            var t3 = t1.ContinueWith(t =>
            {
                int result;
                stack.TryPop(out result);
                Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
            });

            //等待t2和t3执行完
            Task.WaitAll(t2, t3);

            //t7串行执行
            var t4 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("当前集合元素个数:{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);
            });
            t4.Wait();
        }
    }
}

Program

  子任务:

金沙注册送58 30金沙注册送58 31

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main()
        {
            Task<string[]> parent = new Task<string[]>(state =>
            {
                Console.WriteLine(state);
                string[] result = new string[2];
                //创建并启动子任务
                new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start();
                new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start();
                return result;
            }, "我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会结束执行。");
            //任务处理完成后执行的操作
            parent.ContinueWith(t =>
            {
                Array.ForEach(t.Result, r => Console.WriteLine(r));
            });
            //启动父任务
            parent.Start();
            //等待任务结束 Wait只能等待父线程结束,没办法等到父线程的ContinueWith结束
            //parent.Wait();
            Console.ReadLine();

        }
    }
}

Program

  动态并行(TaskCreationOptions.AttachedToParent)
父任务等待全体子职分到位后 整个任务才算完成

金沙注册送58 32金沙注册送58 33

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

namespace ConsoleApp1
{
    class Node
    {
        public Node Left { get; set; }
        public Node Right { get; set; }
        public string Text { get; set; }
    }


    class Program
    {
        static Node GetNode()
        {
            Node root = new Node
            {
                Left = new Node
                {
                    Left = new Node
                    {
                        Text = "L-L"
                    },
                    Right = new Node
                    {
                        Text = "L-R"
                    },
                    Text = "L"
                },
                Right = new Node
                {
                    Left = new Node
                    {
                        Text = "R-L"
                    },
                    Right = new Node
                    {
                        Text = "R-R"
                    },
                    Text = "R"
                },
                Text = "Root"
            };
            return root;
        }

        static void Main(string[] args)
        {
            Node root = GetNode();
            DisplayTree(root);
        }

        static void DisplayTree(Node root)
        {
            var task = Task.Factory.StartNew(() => DisplayNode(root),
                                            CancellationToken.None,
                                            TaskCreationOptions.None,
                                            TaskScheduler.Default);
            task.Wait();
        }

        static void DisplayNode(Node current)
        {

            if (current.Left != null)
                Task.Factory.StartNew(() => DisplayNode(current.Left),
                                            CancellationToken.None,
                                            TaskCreationOptions.AttachedToParent,
                                            TaskScheduler.Default);
            if (current.Right != null)
                Task.Factory.StartNew(() => DisplayNode(current.Right),
                                            CancellationToken.None,
                                            TaskCreationOptions.AttachedToParent,
                                            TaskScheduler.Default);
            Console.WriteLine("当前节点的值为{0};处理的ThreadId={1}", current.Text, Thread.CurrentThread.ManagedThreadId);
        }
    }
}

Program

  二.三、打消职责 CancellationTokenSource

金沙注册送58 34金沙注册送58 35

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

namespace ConsoleApp1
{
    class Program
    {
        private static int TaskMethod(string name, int seconds, CancellationToken token)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            for (int i = 0; i < seconds; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                if (token.IsCancellationRequested) return -1;
            }
            return 42 * seconds;
        }

        private static void Main(string[] args)
        {
            var cts = new CancellationTokenSource();
            var longTask = new Task<int>(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);
            Console.WriteLine(longTask.Status);
            cts.Cancel();
            Console.WriteLine(longTask.Status);
            Console.WriteLine("First task has been cancelled before execution");
            cts = new CancellationTokenSource();
            longTask = new Task<int>(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);
            longTask.Start();
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine(longTask.Status);
            }
            cts.Cancel();
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine(longTask.Status);
            }

            Console.WriteLine("A task has been completed with result {0}.", longTask.Result);
        }
    }
}

Program

  2.肆、处理职责中的分外
  单个职务:

金沙注册送58 36金沙注册送58 37

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

namespace ConsoleApp1
{
    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on a thread id {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;
        }

        static void Main(string[] args)
        {
            try
            {
                Task<int> task = Task.Run(() => TaskMethod("Task 2", 2));
                int result = task.GetAwaiter().GetResult();
                Console.WriteLine("Result: {0}", result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Task 2 Exception caught: {0}", ex.Message);
            }
            Console.WriteLine("----------------------------------------------");
            Console.WriteLine();
        }
    }
}

Program

  两个职责:

金沙注册送58 38金沙注册送58 39

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

namespace ConsoleApp1
{
    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            throw new Exception(string.Format("Task {0} Boom!", name));
            return 42 * seconds;
        }


        public static void Main(string[] args)
        {
            try
            {
                var t1 = new Task<int>(() => TaskMethod("Task 3", 3));
                var t2 = new Task<int>(() => TaskMethod("Task 4", 2));
                var complexTask = Task.WhenAll(t1, t2);
                var exceptionHandler = complexTask.ContinueWith(t =>
                        Console.WriteLine("Result: {0}", t.Result),
                        TaskContinuationOptions.OnlyOnFaulted
                    );
                t1.Start();
                t2.Start();
                Task.WaitAll(t1, t2);
            }
            catch (AggregateException ex)
            {
                ex.Handle(exception =>
                {
                    Console.WriteLine(exception.Message);
                    return true;
                });
            }
        }
    }
}

Program

    async/await的方式:

金沙注册送58 40金沙注册送58 41

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

namespace ConsoleApp1
{
    class Program
    {
        static async Task ThrowNotImplementedExceptionAsync()
        {
            throw new NotImplementedException();
        }

        static async Task ThrowInvalidOperationExceptionAsync()
        {
            throw new InvalidOperationException();
        }

        static async Task Normal()
        {
            await Fun();
        }

        static Task Fun()
        {
            return Task.Run(() =>
            {
                for (int i = 1; i <= 10; i++)
                {
                    Console.WriteLine("i={0}", i);
                    Thread.Sleep(200);
                }
            });
        }

        static async Task ObserveOneExceptionAsync()
        {
            var task1 = ThrowNotImplementedExceptionAsync();
            var task2 = ThrowInvalidOperationExceptionAsync();
            var task3 = Normal();


            try
            {
                //异步的方式
                Task allTasks = Task.WhenAll(task1, task2, task3);
                await allTasks;
                //同步的方式
                //Task.WaitAll(task1, task2, task3);
            }
            catch (NotImplementedException ex)
            {
                Console.WriteLine("task1 任务报错!");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("task2 任务报错!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("任务报错!");
            }

        }

        public static void Main()
        {
            Task task = ObserveOneExceptionAsync();
            Console.WriteLine("主线程继续运行........");
            task.Wait();
        }
    }
}

Program

  2.5、Task.FromResult的应用

金沙注册送58 42金沙注册送58 43

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static IDictionary<string, string> cache = new Dictionary<string, string>()
        {
            {"0001","A"},
            {"0002","B"},
            {"0003","C"},
            {"0004","D"},
            {"0005","E"},
            {"0006","F"},
        };

        public static void Main()
        {
            Task<string> task = GetValueFromCache("0006");
            Console.WriteLine("主程序继续执行。。。。");
            string result = task.Result;
            Console.WriteLine("result={0}", result);

        }

        private static Task<string> GetValueFromCache(string key)
        {
            Console.WriteLine("GetValueFromCache开始执行。。。。");
            string result = string.Empty;
            //Task.Delay(5000);
            Thread.Sleep(5000);
            Console.WriteLine("GetValueFromCache继续执行。。。。");
            if (cache.TryGetValue(key, out result))
            {
                return Task.FromResult(result);
            }
            return Task.FromResult("");
        }

    }
}

Program

  二.6、使用IProgress达成异步编制程序的历程布告
  IProgress<in T>只提供了二个方法void Report(T
value),通过Report方法把1个T类型的值报告给IProgress,然后IProgress<in
T>的兑现类Progress<in
T>的构造函数接收类型为Action<T>的形参,通过那些委托让进程展现在UI界面中。

金沙注册送58 44金沙注册送58 45

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

namespace ConsoleApp1
{
    class Program
    {
        static void DoProcessing(IProgress<int> progress)
        {
            for (int i = 0; i <= 100; ++i)
            {
                Thread.Sleep(100);
                if (progress != null)
                {
                    progress.Report(i);
                }
            }
        }

        static async Task Display()
        {
            //当前线程
            var progress = new Progress<int>(percent =>
            {
                Console.Clear();
                Console.Write("{0}%", percent);
            });
            //线程池线程
            await Task.Run(() => DoProcessing(progress));
            Console.WriteLine("");
            Console.WriteLine("结束");
        }

        public static void Main()
        {
            Task task = Display();
            task.Wait();
        }
    }
}

Program

  2.7、Factory.FromAsync的应用
(简APM情势(委托)转换为天职)(BeginXXX和EndXXX)
  带回调格局的

金沙注册送58 46金沙注册送58 47

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

namespace ConsoleApp1
{
    class Program
    {
        private delegate string AsynchronousTask(string threadName);

        private static string Test(string threadName)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Thread.CurrentThread.Name = threadName;
            return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
        }

        private static void Callback(IAsyncResult ar)
        {
            Console.WriteLine("Starting a callback...");
            Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState);
            Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
            Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
        }

        //执行的流程是 先执行Test--->Callback--->task.ContinueWith
        static void Main(string[] args)
        {
            AsynchronousTask d = Test;
            Console.WriteLine("Option 1");
            Task<string> task = Task<string>.Factory.FromAsync(
                d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine("Callback is finished, now running a continuation! Result: {0}",
                t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);

        }
    }
}

Program

  不带回调形式的

金沙注册送58 48金沙注册送58 49

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

namespace ConsoleApp1
{
    class Program
    {
        private delegate string AsynchronousTask(string threadName);

        private static string Test(string threadName)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Thread.CurrentThread.Name = threadName;
            return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
        }

        //执行的流程是 先执行Test--->task.ContinueWith
        static void Main(string[] args)
        {
            AsynchronousTask d = Test;
            Task<string> task = Task<string>.Factory.FromAsync(
                d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");
            task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",
                t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);

        }
    }
}

Program

 

相关文章

网站地图xml地图