The Task Parallel Library (TPL) is based on the concept of a task, which represents an asynchronous operation. In
some ways, a task resembles a thread or ThreadPool work item, but at a higher
level of abstraction. The term task parallelism refers to one or more
independent tasks running concurrently. Tasks provide two primary benefits:

  • More efficient and more scalable use of system resources.

    Behind the scenes, tasks are queued to the ThreadPool,
    which has been enhanced with algorithms that determine and adjust to the number of threads and that provide load balancing to maximize throughput. This makes tasks relatively lightweight, and you can create many of them
    to enable fine-grained parallelism.

  • More programmatic control than is possible with a thread or work item.

    Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

For both of these reasons, in the .NET Framework, TPL is the preferred API for writing multi-threaded, asynchronous, and parallel code.

  • Creating and Running Tasks Implicitly

The Parallel.Invoke method
provides a convenient way to run any number of arbitrary statements concurrently. Just
pass in an Action delegate for each item of work. The
easiest way to create these delegates is to use lambda expressions. The
lambda expression can either call a named method or provide the code inline. The
following example shows a basic Invoke call that creates
and starts two tasks that run concurrently. The
first task is represented by a lambda expression that calls a method named DoSomeWork, and the second task is represented by a lambda expression that calls a method
named DoSomeOtherWork.

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

The
number of Task instances that are created behind the scenes by Invoke is
not necessarily equal to the number of delegates that are provided. The
TPL may employ various optimizations, especially with large numbers of delegates.

For
greater control over task execution or to return a value from the task, you have to work with Task objects
more explicitly.

  • Creating and Running Tasks Explicitly

    • A
      task that does not return a value is represented by the System.Threading.Tasks.Task class. A
      task that returns a value is represented by the System.Threading.Tasks.Task<TResult> class, which
      inherits from Task. The
      task object handles the infrastructure details and provides methods and properties that are accessible from the calling thread throughout the lifetime of the task. For
      example, you can access the Status property of a task at any time to
      determine whether it has started running, ran to completion, was canceled, or has thrown an exception. The
      status is represented by a TaskStatus enumeration.
    • When
      you create a task, you give it a user delegate that encapsulates the code that the task will execute. The
      delegate can be expressed as a named delegate, an anonymous method, or a lambda expression. Lambda
      expressions can contain a call to a named method, as shown in the following example. Note
      that the example includes a call to the Task.Wait method to ensure that
      the task completes execution before the console mode application ends.
    • You
      can also use the Task.Run methods to create and start a task in one operation. To
      manage the task, the Run methods use the default task scheduler, regardless
      of which task scheduler is associated with the current thread. The Run methods
      are the preferred way to create and start tasks when more control over the creation and scheduling of the task is not needed.
    • You
      can also use the TaskFactory.StartNew method to create and start
      a task in one operation. Use
      this method when creation and scheduling do not have to be separated and you require additional task creation options or the use of a specific scheduler, or when you need to pass additional state into the task through its AsyncState property,
      as shown in the following example.
    • Task and Task<TResult> each
      expose a static Factory property that returns a default instance of TaskFactory,
      so that you can call the method as Task.Factory.StartNew(). Also,
      in the following example, because the tasks are of type System.Threading.Tasks.Task<TResult>, they
      each have a public Task<TResult>.Result property that contains the result of the computation. The
      tasks run asynchronously and may complete in any order. If
      the Result property is accessed before the computation finishes, the property blocks the calling thread until the value
      is available.
    • When
      you use a lambda expression to create a delegate, you have access to all the variables that are visible at that point in your source code. However,
      in some cases, most notably within loops, a lambda doesn't capture the variable as expected. It
      only captures the final value, not the value as it mutates after each iteration.
  • Waiting for Tasks to Finish
    • The System.Threading.Tasks.Task and System.Threading.Tasks.Task<TResult> types
      provide several overloads of the Task.Wait and Task<TResult>.Wait methods
      that enable you to wait for a task to finish. In addition, overloads of the static Task.WaitAll and Task.WaitAny methods
      let you wait for any or all of an array of tasks to finish.
    • Typically, you would wait for a task for one of these reasons:
      • The main thread depends on the final result computed by a task.
      • You have to handle exceptions that might be thrown from the task.
      • The application may terminate before all tasks have completed execution. For
        example, console applications will terminate as soon as all synchronous code in Main (the application entry point) has executed.
    • When
      you wait for a task, you implicitly wait for all children of that task that were created by using the TaskCreationOptions.AttachedToParent option. Task.Wait returns
      immediately if the task has already completed. Any
      exceptions raised by a task will be thrown by a Wait method, even if the Wait method
      was called after the task completed.

Task Parallelism的更多相关文章

  1. Concurrency != Parallelism

    前段时间在公司给大家分享GO语言的一些特性,然后讲到了并发概念,大家表示很迷茫,然后分享过程中我拿来了Rob Pike大神的Slides <Concurrency is not Parallel ...

  2. Task Cancellation: Parallel Programming

    http://beyondrelational.com/modules/2/blogs/79/posts/11524/task-cancellation-parallel-programming-ii ...

  3. Task 和 ThreadPool

    在C#中 TASK 和 ThreadPool 都可以完成多任务并行的工作.但是 TASK实际上是微软定义好的,基于 ThreadPool 的一个类.这里面微软做了很多优化工作. Task Parall ...

  4. task optimization

    Requirements: Tasks have Dependencies Running the task in Multi thread Links http://en.wikipedia.org ...

  5. 【C# Task】开篇

    概览 在学task类之前必须学习线程的知识. 以下是task命名空间的类的结构图 1.2种任务类型: 有返回值task<TResult> .无返回值task. 2.2座任务工厂 TaskF ...

  6. .NET并行编程1 - 并行模式

    设计模式——.net并行编程,清华大学出版的中译本. 相关资源地址主页面: http://parallelpatterns.codeplex.com/ 代码下载: http://parallelpat ...

  7. storm 配置,呵呵。

    配置项 配置说明 storm.zookeeper.servers ZooKeeper服务器列表 storm.zookeeper.port ZooKeeper连接端口 storm.local.dir s ...

  8. Storm配置项详解【转】

    Storm配置项详解 ——阿里数据平台技术博客:storm配置项详解 什么是Storm? Storm是twitter开源的一套实时数据处理框架,基于该框架你可以通过简单的编程来实现对数据流的实时处理变 ...

  9. C#随学随记

    1.Microsoft.NET是基于Windows平台的一种技术(简称.NET),它包含了能在.NET Framework平台运行的所有语言..NET Framework是微软为开发应用程序创建的一个 ...

随机推荐

  1. PHP 根据两点的坐标计算之间的距离

    define('PI',3.1415926535898); define('EARTH_RADIUS',6378.137); //计算范围,可以做搜索用户 function GetRange($lat ...

  2. c# 运行大运算程序主窗体卡掉的解决

    写了一个运算过滤大文本的程序, 其中方法里边使用了多线程,并行线程等方法.  但主窗体控件直接使用此方法时,页面卡顿.所以主线程被堵塞. 代码如下, splitfile 这个方法运行时页面卡顿,阻塞了 ...

  3. L1-006 连续因子(20)(思路+测试点分析)

    L1-006 连续因子(20 分) 一个正整数 N 的因子中可能存在若干连续的数字.例如 630 可以分解为 3×5×6×7,其中 5.6.7 就是 3 个连续的数字.给定任一正整数 N,要求编写程序 ...

  4. Android.Tools.Ant

    ant 1. ant手册翻译 ant手册翻译是一项大工程!!!!!! ant在线手册的链接好不明确. 2. ant 支持for循环 安装ant-contrib Ref[1.1]. 要在ant的buil ...

  5. 洛谷1312 Mayan游戏

    原题链接 讨厌这种大搜索题 基本就是模拟搜索,注意细节即可. 以下是我用的两个剪枝: 将块向左移的前提是左边为空,因为该题要求先右后左,所以若左边有块,那么在上一次搜索向右移的时候一定会搜过,且字典序 ...

  6. UOJ 274 温暖会指引我们前进 - LCT

    Solution 更新掉路径上温暖度最小的边就可以了~ Code #include<cstdio> #include<cstring> #include<algorith ...

  7. [线段树]picture

    PICTURE 题目描述 N(N<5000) 张矩形的海报,照片和其他同样形状的图片贴在墙上.它们的边都是垂直的或水平的.每个矩形可以部分或者全部覆盖其他矩形.所有的矩形组成的集合的轮廓称为周长 ...

  8. sqli盲注自用脚本

    盲注脚本 # -*- coding:utf-8 -*- import requests import re url = "http://123.206.87.240:8002/chengji ...

  9. js Array 方法总结

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. 通过 Spring Security配置 解决X-Frame-Options deny 造成的页面空白 iframe调用问题

    spring Security下,X-Frame-Options默认为DENY,非Spring Security环境下,X-Frame-Options的默认大多也是DENY,这种情况下,浏览器拒绝当前 ...