C#笔记23:多线程之Task(并行编程)

来源:互联网 发布:淘宝怎么看购买关键词 编辑:程序博客网 时间:2024/04/30 05:12

作者:Luminji

转自:http://www.cnblogs.com/luminji/archive/2010/09/19/1830837.html


C#笔记23:多线程之Task(并行编程)

 

1:Task是什么

2:任务取消

3:TPL 和传统 .NET 异步编程

 

    任务并行库 (TPL) 是 .NET Framework 4 版的 System.Threading 和 System.Threading.Tasks 命名空间中的一组公共类型和 API。TPL 的目的在于简化向应用程序中添加并行性和并发性的过程,从而提高开发人员的工作效率。 TPL 会动态地按比例调节并发程度,以便最有效地使用所有可用的处理器。此外,TPL 还处理工作分区、ThreadPool 上的线程调度、取消支持、状态管理以及其他低级别的细节操作。通过使用 TPL,您可以在将精力集中于程序要完成的工作,同时最大程度地提高代码的性能。

 

1:Task是什么

    表示一个异步操作。它是异步操作的首选方式。Task是FRAMEWORK4中的新特性,封装了以前的Thread,并管理Thread。

    任务由 System.Threading.Tasks..::.Task 类表示。返回值的任务由 System.Threading.Tasks..::.Task<(Of <(TResult>)>) 类表示,该类从 Task 继承。任务对象处理基础结构详细信息,并提供可在任务的整个生存期内从调用线程访问的方法和属性。例如,可以随时访问任务的 Status 属性,以确定它是已开始运行、已完成运行、已取消还是引发了异常。状态由 TaskStatus 枚举表示。

 

2:任务取消

namespace CancellationWithOCE{    using System;    using System.Threading;    using System.Threading.Tasks;    class Program    {        static void Main(string[] args)        {            Console.WriteLine("Press any key to start. Press 'c' to cancel.");            Console.ReadKey();            var tokenSource = new CancellationTokenSource();            var token = tokenSource.Token;            // Store references to the tasks so that we can wait on them and            // observe their status after cancellation.            Task[] tasks = new Task[10];            // Request cancellation of a single task when the token source is canceled.            // Pass the token to the user delegate, and also to the task so it can             // handle the exception correctly.            tasks[0] = Task.Factory.StartNew(() => DoSomeWork(1, token), token);            // Request cancellation of a task and its children. Note the token is passed            // to (1) the user delegate and (2) as the second argument to StartNew, so             // that the task instance can correctly handle the OperationCanceledException.            tasks[1] = Task.Factory.StartNew(() =>            {                // Create some cancelable child tasks.                for (int i = 2; i < 10; i++)                {                    // For each child task, pass the same token                    // to each user delegate and to StartNew.                    tasks[i] = Task.Factory.StartNew(iteration =>                                DoSomeWork((int)iteration, token), i, token);                }                // Passing the same token again to do work on the parent task.                 // All will be signaled by the call to tokenSource.Cancel below.                DoSomeWork(2, token);            }, token);            // Give the tasks a second to start.            Thread.Sleep(1000);            // Request cancellation from the UI thread.            if (Console.ReadKey().KeyChar == 'c')            {                tokenSource.Cancel();                Console.WriteLine("\nTask cancellation requested.");                // Optional: Observe the change in the Status property on the task.                // It is not necessary to wait on tasks that have canceled. However,                // if you do wait, you must enclose the call in a try-catch block to                // catch the OperationCanceledExceptions that are thrown. If you do                 // not wait, no OCE is thrown if the token that was passed to the                 // StartNew method is the same token that requested the cancellation.                #region Optional_WaitOnTasksToComplete                try                {                    Task.WaitAll(tasks);                }                catch (AggregateException e)                {                    // For demonstration purposes, show the OCE message.                    foreach (var v in e.InnerExceptions)                        Console.WriteLine("msg: " + v.Message);                }                // Prove that the tasks are now all in a canceled state.                for (int i = 0; i < tasks.Length; i++)                    Console.WriteLine("task[{0}] status is now {1}", i, tasks[i].Status);                #endregion            }            // Keep the console window open while the            // task completes its output.            Console.ReadLine();        }        static void DoSomeWork(int taskNum, CancellationToken ct)        {            // Was cancellation already requested?            if (ct.IsCancellationRequested)            {                Console.WriteLine("We were cancelled before we got started.");                Console.WriteLine("Press Enter to quit.");                ct.ThrowIfCancellationRequested();            }            int maxIterations = 1000;            // NOTE!!! A benign "OperationCanceledException was unhandled            // by user code" error might be raised here. Press F5 to continue. Or,            //  to avoid the error, uncheck the "Enable Just My Code"            // option under Tools > Options > Debugging.            for (int i = 0; i < maxIterations; i++)            {                // Do a bit of work. Not too much.                var sw = new SpinWait();                for (int j = 0; j < 3000; j++) sw.SpinOnce();                Console.WriteLine("...{0} ", taskNum);                if (ct.IsCancellationRequested)                {                    Console.WriteLine("bye from {0}.", taskNum);                    Console.WriteLine("\nPress Enter to quit.");                    ct.ThrowIfCancellationRequested();                }            }        }    }}

3:TPL 和传统 .NET 异步编程

    见http://msdn.microsoft.com/zh-cn/library/dd997423.aspx。


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 刚开的淘宝店铺没有人买东西怎么办 开了一家龙虾店生意很淡怎么办? 新买的皮质小白鞋有点板脚怎么办 手机无效安装包与系统不兼容怎么办 发好的海参放进速冻后变小了怎么办 厨房地砖下面的下水管漏水怎么办? 埋在地下的暖气管漏水怎么办 安装个视频播放器视频全没了怎么办 奇迹mu圣导转职任务打不过怎么办 丈夫死后房产证过给妻子怎么办 学业与志愿活动冲突时你会怎么办 往宅正门前面有半园幕墙玻璃怎么办 模拟城市5石油抽干了怎么办 一户一宅我父亲没有宅基怎么办? 在日本坐新干线期间车票丢了怎么办 街电共享充电宝丢了怎么办 征兵体检时做过疝气手术怎么办 百度网盘手机储存空间不足怎么办 在家带孩子老公不给生活费怎么办 手机蚂蚁浏览器先锋资源没了怎么办 当你发现你的爱人和别人暧昧怎么办 当你的爱人不再爱的时候该怎么办 基督徒的婚姻不是上帝的旨意怎么办 音乐酒吧客人老是要上台唱歌怎么办 高一孩子学习没有动力家长怎么办 我不想当公司监事法人不同意怎么办 领导让我当组长我不想当怎么办 如果你是班委你不想当了怎么办 孩子读初一爱和同学打架怎么办 陌陌情感连线部分功能被限制怎么办 华为荣耀7x密码忘了怎么办 华为荣耀7x应用锁密码忘了怎么办 同学群里有人发低俗信息怎么办 小孩读英语绘本大人不会翻译怎么办 东西掉到手刹缝里面了怎么办 泰拉瑞亚猩红之地蔓延到家里怎么办 三星r.467玩dnf闪退怎么办 美团外卖不小心撞到汽车怎么办 如果你在战场上遇到华裔美军怎么办 衣服洗完了干了后发黄怎么办 毛衣起球怎么办学会这几个小妙招