澳门新葡萄京娱乐网站-澳门新葡萄京888官网-所有平台

热门关键词: 澳门新葡萄京娱乐网站,澳门新葡萄京888官网

0并行库介绍

作者: 编程知识  发布:2019-12-13

1、Task的优势
  ThreadPool相比Thread来讲具有了非常多优势,然则ThreadPool却又存在有的采纳上的不便利。例如:
  ◆ ThreadPool不支持线程的废除、落成、失利公告等交互作用性操作;
  ◆ ThreadPool不帮忙线程实施的前后相继次序;
  现在,要是开采者要达成上述效率,必要形成超多非常的劳作,今后,FCL中提供了叁个功能更刚劲的定义:Task。Task在线程池的根基上海展览中心开了优化,并提供了越来越多的API。在FCL4.0中,如若大家要编写多线程程序,Task鲜明已经优化古板的方法。
  以下是三个粗略的天职示例:

 

Task和ThreadPool的功能看似,能够用来创建一些轻量级的并行职分。对于将一个职分放进线程池     ThreadPool.QueueUserWorkItem(A卡塔尔(قطر‎;

图片 1图片 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有着更加多的效应,更加便利大家选择。

Program

Task和ThreadPool的机能周围,能够用来成立一些轻量级的并行职务。对于将贰个职分放进线程池
    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、Task的用法
  2.1、创造任务
  无再次回到值的章程
  方式1:
  var t1 = new Task(() => TaskMethod("Task 1"));
  t1.Start();
  Task.WaitAll(t1卡塔尔(英语:State of Qatar);//等待全体职责实现
  注:
  任务的情况:
  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();

  方式3:
  Task.Factory.StartNew((卡塔尔国 => TaskMethod("Task 3"卡塔尔卡塔尔国; 直接异步的措施
  或者
  var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));
  Task.WaitAll(t3卡塔尔(英语:State of Qatar);//等待全数职责完结
  注:
  任务的气象:
  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 });
    }

要么大家还足以如此写:

图片 3图片 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);

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并从未立刻实行,须要手动调用t1.Start(卡塔尔(قطر‎来试行(相通于线程,需求手动实施)。而艺术2开立的Task是马上实践的(相仿于线程池,是机关施行的),从这三种方法的函数名称也得以看看那或多或少。

图片 5图片 6

上边大家来大约的牵线一下Task的主题用法:

等待Task完成

等待Task完毕的也可能有两种:

  1. 调用Task的积极分子函数t.Wait(卡塔尔(قطر‎。
  2. 调用Task的静态函数Task.WaitAll(卡塔尔国或Task.WaitAny(卡塔尔国。

那三种方法和.net中常用的WaitHandle大约,这里就相当少介绍了。

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);

那二种艺术实乃同等的,第后生可畏种格局之中也流传了私下认可的TaskFactory——Task.Factory。TaskFactory起着对Task进行创办和调治管理的效率,相像于早先CTP版中的TaskManager,关于那个指标,后续会独自写生龙活虎篇著作介绍。

取消Task

打消Task的办法较CTP的时候复杂和有力了众多,后续加贰个单身的稿子单独介绍。

Program

开首运转Task

在上述二种制造Task情势中,格局1成立的Task并不曾即时举行,必要手动调用t1.Start(卡塔尔(英语:State of Qatar)来实践(相符于线程,供给手动施行)。而艺术2开立的Task是立刻施行的(雷同于线程池,是半自动实施的),从那二种办法的函数名称也能够见见那一点。

丰富管理

当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);     }

  带重返值的措施
  方式4:
  Task<int> task = CreateTask("Task 1");
  task.Start();
  int result = task.Result;

等待Task完成

等候Task完结的也会有二种:

  1. 调用Task的积极分子函数t.Wait(卡塔尔(英语:State of Qatar)。
  2. 调用Task的静态函数Task.WaitAll(卡塔尔国或Task.WaitAny(卡塔尔(英语:State of Qatar)。

那三种办法和.net中常用的WaitHandle大约,这里就超级少介绍了。

获得Task的再次来到值

在CTP版本中,是经过Fucture<>类来获取带重临值的Task的,以后豆蔻梢头度将类改名叫Task<>了,进而达成命名格局的拜见。使用办法大约千篇黄金年代律,正是多了三个Result属性,能够在Task推行到位后拿走再次来到值。示比如下:

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

图片 7图片 8

取消Task

收回Task的办法较CTP的时候复杂和有力了数不尽,后续加叁个单身的稿子单独介绍。

其它

在Task中还应该有为数不菲不行政管理用的职责调解和错误管理等的不二秘籍和总体性,它们使得并发操作变得更为强盛和轻便,现在会时有时无介绍这么些文化。

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);
    }

Program

得到Task的重返值

在CTP版本中,是因而Fucture<>类来获取带重临值的Task的,今后早已将类改名字为Task<>了,从而完成命名方式的群集。使用情势大概等同,正是多了贰个Result属性,能够在Task试行到位后收获重回值。示举例下:

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

 

 

    async/await的实现:

图片 9图片 10

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

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

图片 11图片 12

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

   职责的串行:

图片 13图片 14

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

  子任务:

图片 15图片 16

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卡塔尔国父义务等待全部子义务到位后 整个职责才算实现

图片 17图片 18

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

  2.3、裁撤职责 CancellationTokenSource

图片 19图片 20

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.4、管理职分中的非常
  单个职责:

图片 21图片 22

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

  多少个职分:

图片 23图片 24

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的方式:

图片 25图片 26

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的应用

图片 27图片 28

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

  2.6、使用IProgress完成异步编程的长河布告
  IProgress<in T>只提供了三个办法void Report(T value卡塔尔国,通过Report方法把一个T类型的值报告给IProgress,然后IProgress<in T>的兑现类Progress<in T>的构造函数采取类型为Action<T>的形参,通过那么些委托让进度展现在UI分界面中。

图片 29图片 30

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格局(委托卡塔尔(英语:State of Qatar)转换为职务卡塔尔(قطر‎(BeginXXX和EndXXX卡塔尔(قطر‎
  带回调方式的

图片 31图片 32

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

  不带回调方式的

图片 33图片 34

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

 

本文由澳门新葡萄京娱乐网站发布于编程知识,转载请注明出处:0并行库介绍

关键词:

上一篇:JS对象与json字符串格式,自个儿计算的
下一篇:没有了