本文内容

  • 并行编程
  • 任务并行
    • 隐式创建和运行任务
    • 显式创建和运行任务
    • 任务 ID
    • 任务创建选项
    • 创建任务延续
    • 创建分离的子任务
    • 创建子任务
    • 等待任务完成
    • 组合任务
    • 任务中的异常处理
    • 取消任务
    • TaskFactory 类
    • 无委托的任务
    • 相关数据结构
  • 参考资料

下载 Demo

下载 Samples for Parallel Programming with .net framework

并行编程


多核 CPU 已经相当普遍,使得多个线程能够同时执行。将代码并行化,工作也就分摊到多个 CPU 上。

过去,并行化需要线程和锁的低级操作。而 Visual Studio 2010 和 .NET Framework 4 开始提供了新的运行时、新的类库类型以及新的诊断工具,从而增强了对并行编程的支持。这些功能简化了并行开发,通过固有方法编写高效、细化且可伸缩的并行代码,而不必直接处理线程或线程池。

下图从较高层面上概述了 .NET Framework 4 中的并行编程体系结构。

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

从 .NET Framework 4 开始,TPL 是编写多线程代码和并行代码的首选方法。但并不是所有代码都适合并行化,例如,如果某个循环在每次迭代时只执行少量工作,或它在很多次迭代时都不运行,那么并行化的开销可能导致代码运行更慢。 此外,像任何多线程代码一样,并行化会增加程序执行的复杂性。 尽管 TPL 简化了多线程方案,但建议对线程处理概念(例如,锁、死锁和争用条件)进行基本了解,以便能够有效地使用 TPL。

任务并行


“任务并行”是指一个或多个独立的任务同时运行。好处当然是系统资源的使用效率更高,可伸缩性更好;对于线程或工作项,可以使用更多的编程控件。因此,在 .NET Framework 中,TPL 是用于编写多线程、异步和并行代码的首选 API。

隐式创建和运行任务

Parallel.Invoke 方法提供了一种简便方式,可同时运行任意数量的任意语句。只需为每个工作项传入 Action 委托即可。

下面的示例演示 Invoke 调用,创建并启动同时运行三个任务。将对共享数据达尔文的《物种起源》执行三项操作:最长的词、最频繁出现的词和字数。这些操作都不修改源,因此它们可以直接并行执行。

  1. using System;

  1. using System.Linq;

  1. using System.Text;

  1. using System.Threading.Tasks;

  1.  

  1. namespace ParallelInvokeDemo

  1. {

  1. class Program

  1. {

  1. static void Main(string[] args)

  1. {

  1. // Retrieve Darwin's "Origin of the Species" from Gutenberg.org.

  1. string[] words = CreateWordArray();

  1.  

  1.  

  1. // Perform three tasks in parallel on the source array

  1. Parallel.Invoke(() =>

  1. {

  1. Console.WriteLine("Begin first task...");

  1. GetLongestWord(words);

  1. }, // close first Action

  1.  

  1. () =>

  1. {

  1. Console.WriteLine("Begin second task...");

  1. GetMostCommonWords(words);

  1. }, //close second Action

  1.  

  1. () =>

  1. {

  1. Console.WriteLine("Begin third task...");

  1. GetCountForWord(words, "species");

  1. } //close third Action

  1. ); //close parallel.invoke

  1.  

  1. Console.WriteLine("Returned from Parallel.Invoke");

  1.  

  1. Console.WriteLine("Press any key to exit.");

  1. Console.ReadKey();

  1. }

  1.  

  1. private static string GetLongestWord(string[] words)

  1. {

  1. var longestWord = (from w in words

  1. orderby w.Length descending

  1. select w).First();

  1.  

  1. Console.WriteLine("Task 1 -- The longest word is {0}", longestWord);

  1. return longestWord;

  1. }

  1.  

  1. private static void GetMostCommonWords(string[] words)

  1. {

  1. var frequencyOrder = from word in words

  1. where word.Length > 6

  1. group word by word into g

  1. orderby g.Count() descending

  1. select g.Key;

  1.  

  1. var commonWords = frequencyOrder.Take(10);

  1.  

  1. StringBuilder sb = new StringBuilder();

  1. sb.AppendLine("Task 2 -- The most common words are:");

  1. foreach (var v in commonWords)

  1. {

  1. sb.AppendLine(" " + v);

  1. }

  1. Console.WriteLine(sb.ToString());

  1. }

  1.  

  1. private static void GetCountForWord(string[] words, string term)

  1. {

  1. var findWord = from word in words

  1. where word.ToUpper().Contains(term.ToUpper())

  1. select word;

  1.  

  1. Console.WriteLine(@"Task 3 -- The word ""{0}"" occurs {1} times.", term, findWord.Count());

  1. }

  1.  

  1. static string[] CreateWordArray()

  1. {

  1. string s = System.IO.File.ReadAllText("Origin of the Species.txt");

  1. // Separate string into an array of words, removing some common punctuation.

  1. return s.Split(

  1. new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '_', '/' },

  1. StringSplitOptions.RemoveEmptyEntries);

  1. }

  1. }

  1. }

  1. //RESULT:

  1. //Begin second task...

  1. //Begin first task...

  1. //Begin third task...

  1. //Task 2 -- The most common words are:

  1. // species

  1. // selection

  1. // varieties

  1. // natural

  1. // animals

  1. // between

  1. // different

  1. // distinct

  1. // several

  1. // conditions

  1.  

  1. //Task 1 -- The longest word is characteristically

  1. //Task 3 -- The word "species" occurs 1927 times.

  1. //Returned from Parallel.Invoke

  1. //Press any key to exit.

为了更好地控制任务执行或从任务返回值,必须更加显式地使用 Task 对象。

显式创建和运行任务

不返回值的任务由 System.Threading.Tasks.Task 类表示。返回值的任务由 System.Threading.Tasks.Task<TResult> 类表示,该类从 Task 继承。

任务对象处理基础结构详细信息,并提供可在任务的整个生存期内从调用线程访问的方法和属性。 例如,可以随时访问任务的 Status 属性,以确定它是已开始运行、已完成运行、已取消还是引发了异常。 状态由 TaskStatus 枚举表示。

在创建任务时,你赋予它一个用户委托,该委托封装该任务将执行的代码。 该委托可以表示为命名的委托、匿名方法或 lambda 表达式。 lambda 表达式可以包含对命名方法的调用,如下面的示例所示。

  1. using System;

  1. using System.Threading;

  1. using System.Threading.Tasks;

  1.  

  1. namespace ExplicitTaskDemo

  1. {

  1. class Program

  1. {

  1. static void Main(string[] args)

  1. {

  1. Thread.CurrentThread.Name = "Main";

  1. // Create a task and supply a user delegate by using a lambda expression.

  1. Task taskA = new Task(() => Console.WriteLine("Hello from taskA."));

  1. // Start the task.

  1. taskA.Start();

  1. // Output a message from the calling thread.

  1. Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name);

  1. taskA.Wait();

  1.  

  1.  

  1.  

  1. //Thread.CurrentThread.Name = "Main";

  1. //// Define and run the task.

  1. //Task taskA = Task.Run(() => Console.WriteLine("Hello from taskA."));

  1. //// Output a message from the calling thread.

  1. //Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name);

  1. //taskA.Wait();

  1.  

  1.  

  1.  

  1. //Thread.CurrentThread.Name = "Main";

  1. //// Better: Create and start the task in one operation.

  1. //Task taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));

  1. //// Output a message from the calling thread.

  1. //Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name);

  1. //taskA.Wait();

  1.  

  1.  

  1.  

  1. Console.WriteLine("Press any Key to Exit.");

  1. Console.ReadKey();

  1. }

  1. }

  1. }

  1. //TaskParallel1 RESULT:

  1. //Hello from thread 'Main'.

  1. //Hello from taskA.

  1. //Press any Key to Exit.

你可以用 new Task(),也可以用 Task.Run(),还可以用 Task.Factory.StartNew(),创建并启动一个任务。其中,Task.Run() 是首选方法;不必将创建和计划分开并且你需要其他任务创建选项或使用特定计划程序时,或者需要通过 AsyncState 属性将其他状态传递到任务时,使用 Task.Factory.StartNew()

任务创建选项

创建任务的大多数 API 提供接受 TaskCreationOptions 枚举参数。 通过指定下列选项之一,可指示任务计划程序如何在线程池中安排任务计划。

  1. using System;

  1. using System.Threading.Tasks;

  1.  

  1. namespace TaskCreationOptionsDemo

  1. {

  1. class Program

  1. {

  1. static void Main(string[] args)

  1. {

  1. var task3 = new Task(() => MyLongRunningMethod(),

  1. TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);

  1. task3.Start();

  1.  

  1. task3.Wait();

  1.  

  1. Console.WriteLine("Press any key to Exit.");

  1. Console.ReadKey();

  1.  

  1. }

  1. static void MyLongRunningMethod()

  1. {

  1. Console.WriteLine("A long, long time ago......");

  1. }

  1. }

  1. }

TaskCreationOptions 参数值

说明

None

未指定任何选项时的默认值。 计划程序将使用其默认试探法来计划任务。

PreferFairness

指定应当计划任务,以使越早创建的任务将更可能越早执行,而越晚创建的任务将更可能越晚执行。

LongRunning

指定该任务表示长时间运行的运算。

AttachedToParent

指定应将任务创建为当前任务(如果存在)的附加子级。 有关更多信息,请参见已附加和已分离的子任务。

DenyChildAttach

指定如果内部任务指定 AttachedToParent 选项,则该任务不会成为附加的子任务。

HideScheduler

指定通过调用特定任务内部的 TaskFactory.StartNew 或 Task<TResult>.ContinueWith 等方法创建的任务的任务计划程序是默认计划程序,而不是正在运行此任务的计划程序。

创建任务延续

使用 Task.ContinueWithTask<TResult>.ContinueWith 方法可以指定在先行任务完成时要启动的任务。 延续任务的委托已传递了对先行任务的引用,因此它可以检查先行任务的状态,并通过检索 Task<TResult>.Result 属性的值将先行任务的输出用作延续任务的输入。

  1. var getData = Task.Factory.StartNew(() =>

  1. {

  1. Random rnd = new Random();

  1. int[] values = new int[100];

  1. for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)

  1. values[ctr] = rnd.Next();

  1.  

  1. return values;

  1. });

  1.  

  1.  

  1. var processData = getData.ContinueWith((x) =>

  1. {

  1. int n = x.Result.Length;

  1. long sum = 0;

  1. double mean;

  1.  

  1. for (int ctr = 0; ctr <= x.Result.GetUpperBound(0); ctr++)

  1. sum += x.Result[ctr];

  1.  

  1. mean = sum / (double)n;

  1. return Tuple.Create(n, sum, mean);

  1. });

  1.  

  1.  

  1. var displayData = processData.ContinueWith((x) =>

  1. {

  1. return String.Format("N={0:N0}, Total = {1:N0}, Mean = {2:N2}",

  1. x.Result.Item1, x.Result.Item2, x.Result.Item3);

  1. });

  1.  

  1.  

  1. Console.WriteLine(displayData.Result);

  1. //N=100, Total = 108,192,345,466, Mean = 1,081,923,454.66

  1. //Press any key to Exit.

也可以用链式写法:

  1. var displayData = Task.Factory.StartNew(() =>

  1. {

  1. Random rnd = new Random();

  1. int[] values = new int[100];

  1. for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)

  1. values[ctr] = rnd.Next();

  1.  

  1. return values;

  1. }).

  1. ContinueWith((x) =>

  1. {

  1. int n = x.Result.Length;

  1. long sum = 0;

  1. double mean;

  1.  

  1. for (int ctr = 0; ctr <= x.Result.GetUpperBound(0); ctr++)

  1. sum += x.Result[ctr];

  1.  

  1. mean = sum / (double)n;

  1. return Tuple.Create(n, sum, mean);

  1. }).

  1. ContinueWith((x) =>

  1. {

  1. return String.Format("N={0:N0}, Total = {1:N0}, Mean = {2:N2}",

  1. x.Result.Item1, x.Result.Item2,

  1. x.Result.Item3);

  1. });

  1.  

  1. Console.WriteLine(displayData.Result);

创建分离的子任务

如果在任务中运行的用户代码创建一个新任务,且未指定 AttachedToParent 选项,则该新任务不采用任何特殊方式与父任务同步。 这种不同步的任务类型称为“分离的嵌套任务”或“分离的子任务”。

  1. var outer = Task.Factory.StartNew(() =>

  1. {

  1. Console.WriteLine("Outer task beginning.");

  1.  

  1. var child = Task.Factory.StartNew(() =>

  1. {

  1. Thread.SpinWait(5000000);

  1. Console.WriteLine("Detached task completed.");

  1. });

  1.  

  1. });

  1.  

  1. outer.Wait();

  1. Console.WriteLine("Outer task completed.");

  1. //The example displays the following output:

  1. //Outer task beginning.

  1. //Outer task completed.

  1. //Detached task completed.

从输出信息看,outer 没有等 child。

创建子任务

如果在一个任务中运行的用户代码创建任务时指定了 AttachedToParent 选项,则该新任务称为父任务的“附加子任务”。 因为父任务隐式地等待所有附加子任务完成,所以你可以使用 AttachedToParent 选项表示结构化的任务并行。

  1. var parent = Task.Factory.StartNew(() =>

  1. {

  1. Console.WriteLine("Parent task beginning.");

  1. for (int ctr = 0; ctr < 10; ctr++)

  1. {

  1. int taskNo = ctr;

  1. Task.Factory.StartNew((x) =>

  1. {

  1. Thread.SpinWait(5000000);

  1. Console.WriteLine("Attached child #{0} completed.",

  1. x);

  1. },

  1. taskNo, TaskCreationOptions.AttachedToParent);

  1. }

  1. });

  1.  

  1. parent.Wait();

  1. Console.WriteLine("Parent task completed.");

  1. //The example displays the following output:

  1. //Parent task beginning.

  1. //Attached child #9 completed.

  1. //Attached child #0 completed.

  1. //Attached child #8 completed.

  1. //Attached child #1 completed.

  1. //Attached child #3 completed.

  1. //Attached child #7 completed.

  1. //Attached child #4 completed.

  1. //Attached child #5 completed.

  1. //Attached child #2 completed.

  1. //Attached child #6 completed.

  1. //Parent task completed.

等待任务完成

System.Threading.Tasks.Task 类型和 System.Threading.Tasks.Task<TResult> 类型提供了 Task.WaitTask<TResult>.Wait 方法的若干重载,使你能够等待任务完成。

此外,使用静态 Task.WaitAllTask.WaitAny 方法的重载可以等待一批任务中的任一任务或所有任务完成。

通常,会出于以下某个原因等待任务:

  • 主线程依赖于任务计算的最终结果。
  • 你必须处理可能从任务引发的异常。
  • 应用程序可以在所有任务执行完毕之前终止。 例如,执行 Main(应用程序入口点)中的所有同步代码后,控制台应用程序将立即终止。

组合任务

Task 类和 Task<TResult> 类提供多种方法,这些方法能够帮助你组合多个任务以实现常见模式,并更好地使用由 C#、Visual Basic 和 F# 提供的异步语言功能。 本节介绍了 WhenAllWhenAnyDelayFromResult<TResult> 方法。

Task.WhenAll 和 Task.WhenAny

  1. using System;

  1. using System.Collections.Generic;

  1. using System.Linq;

  1. using System.Text;

  1. using System.Threading;

  1. using System.Threading.Tasks;

  1.  

  1. namespace TaskWaitAllWaitAnyDemo

  1. {

  1. class Program

  1. {

  1. static Random rand = new Random();

  1.  

  1. static void Main(string[] args)

  1. {

  1. // Wait on a single task with no timeout specified.

  1. Task taskA = Task.Factory.StartNew(() => DoSomeWork(10000000));

  1. taskA.Wait();

  1. Console.WriteLine("taskA has completed.");

  1.  

  1.  

  1. // Wait on a single task with a timeout specified.

  1. Task taskB = Task.Factory.StartNew(() => DoSomeWork(10000000));

  1. taskB.Wait(100); //Wait for 100 ms.

  1.  

  1. if (taskB.IsCompleted)

  1. Console.WriteLine("taskB has completed.");

  1. else

  1. Console.WriteLine("Timed out before taskB completed.");

  1.  

  1. // Wait for all tasks to complete.

  1. Task[] tasks = new Task[10];

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

  1. {

  1. tasks[i] = Task.Factory.StartNew(() => DoSomeWork(10000000));

  1. }

  1. Task.WaitAll(tasks);

  1.  

  1. // Wait for first task to complete.

  1. Task<double>[] tasks2 = new Task<double>[3];

  1.  

  1. // Try three different approaches to the problem. Take the first one.

  1. tasks2[0] = Task<double>.Factory.StartNew(() => TrySolution1());

  1. tasks2[1] = Task<double>.Factory.StartNew(() => TrySolution2());

  1. tasks2[2] = Task<double>.Factory.StartNew(() => TrySolution3());

  1.  

  1.  

  1. int index = Task.WaitAny(tasks2);

  1. double d = tasks2[index].Result;

  1. Console.WriteLine("task[{0}] completed first with result of {1}.", index, d);

  1.  

  1. Console.ReadKey();

  1. }

  1.  

  1. static void DoSomeWork(int val)

  1. {

  1. // Pretend to do something.

  1. Thread.SpinWait(val);

  1. }

  1.  

  1. static double TrySolution1()

  1. {

  1. int i = rand.Next(1000000);

  1. // Simulate work by spinning

  1. Thread.SpinWait(i);

  1. return DateTime.Now.Millisecond;

  1. }

  1. static double TrySolution2()

  1. {

  1. int i = rand.Next(1000000);

  1. // Simulate work by spinning

  1. Thread.SpinWait(i);

  1. return DateTime.Now.Millisecond;

  1. }

  1. static double TrySolution3()

  1. {

  1. int i = rand.Next(1000000);

  1. // Simulate work by spinning

  1. Thread.SpinWait(i);

  1. Thread.SpinWait(1000000);

  1. return DateTime.Now.Millisecond;

  1. }

  1. }

  1. }

  1. //The example displays the following output:

  1. //taskA has completed.

  1. //taskB has completed.

  1. //task[0] completed first with result of 353.

最后一个输出结果是不确定的,因为 int index = Task.WaitAny(tasks2); 语句,task2 任务数组中有一个完成,就可以执行该语句下面的语句。

Task.FromResult<TResult>

  1. using System;

  1. using System.Collections.Concurrent;

  1. using System.Collections.Generic;

  1. using System.Diagnostics;

  1. using System.Linq;

  1. using System.Net;

  1. using System.Text;

  1. using System.Threading.Tasks;

  1.  

  1. namespace TaskFromResultDemo

  1. {

  1. /// <summary>

  1. /// Demonstrates how to use Task<TResult>.FromResult to create a task that holds a pre-computed result.

  1. /// </summary>

  1. class Program

  1. {

  1. // Holds the results of download operations.

  1. static ConcurrentDictionary<string, string> cachedDownloads = new ConcurrentDictionary<string, string>();

  1.  

  1. // Asynchronously downloads the requested resource as a string.

  1. public static Task<string> DownloadStringAsync(string address)

  1. {

  1. // First try to retrieve the content from cache.

  1. string content;

  1. if (cachedDownloads.TryGetValue(address, out content))

  1. {

  1. return Task.FromResult<string>(content);

  1. }

  1.  

  1. // If the result was not in the cache, download the

  1. // string and add it to the cache.

  1. return Task.Run(async () =>

  1. {

  1. content = await new WebClient().DownloadStringTaskAsync(address);

  1. cachedDownloads.TryAdd(address, content);

  1. return content;

  1. });

  1. }

  1.  

  1. static void Main(string[] args)

  1. {

  1. // The URLs to download.

  1. string[] urls = new string[]

  1. {

  1. "http://msdn.microsoft.com",

  1. "http://www.contoso.com",

  1. "http://www.microsoft.com"

  1. };

  1.  

  1. // Used to time download operations.

  1. Stopwatch stopwatch = new Stopwatch();

  1.  

  1. // Compute the time required to download the URLs.

  1. stopwatch.Start();

  1. var downloads = from url in urls

  1. select DownloadStringAsync(url);

  1. Task.WhenAll(downloads).ContinueWith(results =>

  1. {

  1. stopwatch.Stop();

  1.  

  1. // Print the number of characters download and the elapsed time.

  1. Console.WriteLine("Retrieved {0} characters. Elapsed time was {1} ms.",

  1. results.Result.Sum(result => result.Length),

  1. stopwatch.ElapsedMilliseconds);

  1. })

  1. .Wait();

  1.  

  1. // Perform the same operation a second time. The time required

  1. // should be shorter because the results are held in the cache.

  1. stopwatch.Restart();

  1. downloads = from url in urls

  1. select DownloadStringAsync(url);

  1. Task.WhenAll(downloads).ContinueWith(results =>

  1. {

  1. stopwatch.Stop();

  1.  

  1. // Print the number of characters download and the elapsed time.

  1. Console.WriteLine("Retrieved {0} characters. Elapsed time was {1} ms.",

  1. results.Result.Sum(result => result.Length),

  1. stopwatch.ElapsedMilliseconds);

  1. })

  1. .Wait();

  1.  

  1. Console.WriteLine("Press any key to Exit.");

  1. Console.ReadKey();

  1. }

  1. }

  1. }

  1. //The example displays the following output:

  1. //Retrieved 45462 characters. Elapsed time was 23734 ms.

  1. //Retrieved 45462 characters. Elapsed time was 0 ms.

  1. //Press any key to Exit.

任务中的异常处理

当某个任务抛出一个或多个异常时,异常包装在 AggregateException 异常中。 该异常传播回与该任务联接的线程,通常该线程正在等待该任务完成或该线程访问 Result 属性。此行为用于强制实施 .NET Framework 策略 - 默认所有未处理的异常应终止进程。

可以通过将 WaitWaitAllWaitAny 方法,以及 Result 属性放入 try/catch 块中来处理异常。

捕获 System.AggregateException,然后检查其 InnerExceptions 以查看是否存在任何可由程序代码处理的异常。如下代码所示:

  1. static void HandleExceptions()

  1. {

  1. // Assume this is a user-entered string.

  1. string path = @"C:\";

  1.  

  1. // Use this line to throw UnauthorizedAccessException, which we handle.

  1. Task<string[]> task1 = Task<string[]>.Factory.StartNew(() => GetAllFiles(path));

  1.  

  1. // Use this line to throw an exception that is not handled.

  1. // Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); } );

  1. try

  1. {

  1. task1.Wait();

  1. }

  1. catch (AggregateException ae)

  1. {

  1. ae.Handle((x) =>

  1. {

  1. if (x is UnauthorizedAccessException) // This we know how to handle.

  1. {

  1. Console.WriteLine("You do not have permission to access all folders in this path.");

  1. Console.WriteLine("See your network administrator or try another path.");

  1. return true;

  1. }

  1. return false; // Let anything else stop the application.

  1. });

  1.  

  1. }

  1.  

  1. Console.WriteLine("task1 has completed.");

  1. }

  1.  

  1. static string[] GetAllFiles(string str)

  1. {

  1. // Should throw an AccessDenied exception on Vista.

  1. return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories);

  1. }

在此示例中,捕获 System.AggregateException,但不尝试处理任何其内部异常。 而是使用 Flatten 方法从任何嵌套的 AggregateException 实例中提取内部异常,并再次引发直接包含所有内部未处理异常的单个 AggregateException。 展平异常将使其更便于供客户端代码处理。

  1. static void RethrowAllExceptions()

  1. {

  1. // Assume this is a user-entered string.

  1. string path = @"C:\";

  1.  

  1.  

  1. Task<string[]>[] tasks = new Task<string[]>[3];

  1. tasks[0] = Task<string[]>.Factory.StartNew(() => GetAllFiles(path));

  1. tasks[1] = Task<string[]>.Factory.StartNew(() => GetValidExtensions(path));

  1. tasks[2] = Task<string[]>.Factory.StartNew(() => new string[10]);

  1.  

  1.  

  1. //int index = Task.WaitAny(tasks2);

  1. //double d = tasks2[index].Result;

  1. try

  1. {

  1. Task.WaitAll(tasks);

  1. }

  1. catch (AggregateException ae)

  1. {

  1. throw ae.Flatten();

  1. }

  1.  

  1. Console.WriteLine("task1 has completed.");

  1. }

  1.  

  1. static string[] GetValidExtensions(string path)

  1. {

  1. if (path == @"C:\")

  1. throw new ArgumentException("The system root is not a valid path.");

  1.  

  1. return new string[10];

  1. }

取消任务

Task 类支持协作取消,并与 .NET Framework 4 中新增的 System.Threading.CancellationTokenSource 类和 System.Threading.CancellationToken 类完全集成。

创建任务的大多数 API 提供接受 CancellationToken 参数。

  1. var tokenSource2 = new CancellationTokenSource();

  1. CancellationToken ct = tokenSource2.Token;

  1.  

  1. var task = Task.Factory.StartNew(() =>

  1. {

  1. // Were we already canceled?

  1. ct.ThrowIfCancellationRequested();

  1.  

  1. bool moreToDo = true;

  1. while (moreToDo)

  1. {

  1. // Poll on this property if you have to do

  1. // other cleanup before throwing.

  1. if (ct.IsCancellationRequested)

  1. {

  1. // Clean up here, then...

  1. ct.ThrowIfCancellationRequested();

  1. }

  1. }

  1. }, tokenSource2.Token); // Pass same token to StartNew.

  1.  

  1. tokenSource2.Cancel();

  1.  

  1. // Just continue on this thread, or Wait/WaitAll with try-catch:

  1. try

  1. {

  1. task.Wait();

  1. }

  1. catch (AggregateException e)

  1. {

  1. foreach (var v in e.InnerExceptions)

  1. Console.WriteLine(e.Message + " " + v.Message);

  1. }

TaskFactory 类

TaskFactory 类提供静态方法,这些方法封装了用于创建和启动任务和延续任务的一些常用模式。

  • 最常用模式为 StartNew,它在一个语句中创建并启动任务。
  • 从多个先行任务创建延续任务时,请使用 ContinueWhenAll 方法或 ContinueWhenAny 方法,或者它们在 Task<TResult> 类中的等效方法。 有关更多信息,请参见延续任务。
  • 若要在 Task Task<TResult> 实例中封装异步编程模型 BeginXEndX 方法,请使用 FromAsync 方法。

默认的 TaskFactory 可作为 Task 类或 Task<TResult> 类上的静态属性访问。 你还可以直接实例化 TaskFactory 并指定各种选项,包括 CancellationTokenTaskCreationOptions 选项、TaskContinuationOptions 选项或 TaskScheduler。 创建任务工厂时所指定的任何选项将应用于它创建的所有任务,除非 Task 是通过使用 TaskCreationOptions 枚举创建的(在这种情况下,任务的选项重写任务工厂的选项)。

无委托的任务

在某些情况下,可能需要使用 Task 封装由外部组件(而不是你自己的用户委托)执行的某个异步操作。 如果该操作基于异步编程模型 Begin/End 模式,你可以使用 FromAsync 方法。 如果不是这种情况,你可以使用 TaskCompletionSource<TResult> 对象将该操作包装在任务中,并因而获得 Task 可编程性的一些好处,例如对异常传播和延续的支持。

在许多方案中,启用一个 Task<TResult> 来表示外部异步操作非常有用。 出于此目的,提供了 TaskCompletionSource<TResult>。 它允许创建可以分发到使用者的任务,这些使用者可以同其他情况下一样使用该任务的成员。 但是,与大多数任务不同,TaskCompletionSource 创建的任务的状态由 TaskCompletionSource 上的方法显式控制。 这使得要传播到基础任务的外部异步操作能够完成。 分离还确保使用者没有访问对应的 TaskCompletionSource 时不能转换状态。

  1. using System;

  1. using System.Collections.Generic;

  1. using System.Diagnostics;

  1. using System.Linq;

  1. using System.Text;

  1. using System.Threading;

  1. using System.Threading.Tasks;

  1.  

  1. namespace TaskCompletionSourceDemo

  1. {

  1. class Program

  1. {

  1. // Demonstrated features:

  1. // TaskCompletionSource ctor()

  1. // TaskCompletionSource.SetResult()

  1. // TaskCompletionSource.SetException()

  1. // Task.Result

  1. // Expected results:

  1. // The attempt to get t1.Result blocks for ~1000ms until tcs1 gets signaled. 15 is printed out.

  1. // The attempt to get t2.Result blocks for ~1000ms until tcs2 gets signaled. An exception is printed out.

  1. // Documentation:

  1. // http://msdn.microsoft.com/en-us/library/dd449199(VS.100).aspx

  1. static void Main(string[] args)

  1. {

  1. TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();

  1. Task<int> t1 = tcs1.Task;

  1.  

  1. // Start a background task that will complete tcs1.Task

  1. Task.Factory.StartNew(() =>

  1. {

  1. Thread.Sleep(1000);

  1. tcs1.SetResult(15);

  1. });

  1.  

  1. // The attempt to get the result of t1 blocks the current thread until the completion source gets signaled.

  1. // It should be a wait of ~1000 ms.

  1. Stopwatch sw = Stopwatch.StartNew();

  1. int result = t1.Result;

  1. sw.Stop();

  1.  

  1. Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result);

  1.  

  1. // ------------------------------------------------------------------

  1.  

  1. // Alternatively, an exception can be manually set on a TaskCompletionSource.Task

  1. TaskCompletionSource<int> tcs2 = new TaskCompletionSource<int>();

  1. Task<int> t2 = tcs2.Task;

  1.  

  1. // Start a background Task that will complete tcs2.Task with an exception

  1. Task.Factory.StartNew(() =>

  1. {

  1. Thread.Sleep(1000);

  1. tcs2.SetException(new InvalidOperationException("SIMULATED EXCEPTION"));

  1. });

  1.  

  1. // The attempt to get the result of t2 blocks the current thread until the completion source gets signaled with either a result or an exception.

  1. // In either case it should be a wait of ~1000 ms.

  1. sw = Stopwatch.StartNew();

  1. try

  1. {

  1. result = t2.Result;

  1.  

  1. Console.WriteLine("t2.Result succeeded. THIS WAS NOT EXPECTED.");

  1.  

  1. Console.WriteLine("Press any key to Exit.");

  1. Console.ReadKey();

  1. }

  1. catch (AggregateException e)

  1. {

  1. Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds);

  1. Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)");

  1. for (int j = 0; j < e.InnerExceptions.Count; j++)

  1. {

  1. Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());

  1. }

  1.  

  1. Console.WriteLine("Press any key to Exit.");

  1. Console.ReadKey();

  1. }

  1. }

  1. }

  1. }

相关数据结构

TPL 有几种在并行和顺序方案中都有用的新公共类型。 它们包括 System.Collections.Concurrent 命名空间中的一些线程安全的、快速且可缩放的集合类,还包括一些新的同步类型(例如 System.Threading.Semaphore System.Threading.ManualResetEventSlim),对特定类型的工作负荷而言,这些新同步类型比旧的同步类型效率更高。 .NET Framework 4 中的其他新类型(例如 System.Threading.BarrierSystem.Threading.SpinLock)提供了早期版本中未提供的功能。

参考资料


 

下载 Demo

下载 Samples for Parallel Programming with .net framework

.NET 并行编程——任务并行的更多相关文章

  1. .NET 并行编程——数据并行

    本文内容 并行编程 数据并行 环境 计算 PI 矩阵相乘 把目录中的全部图片复制到另一个目录 列出指定目录中的所有文件,包括其子目录 最近,对多线程编程,并行编程,异步编程,这三个概念有点晕了,之前我 ...

  2. 一、并行编程 - 数据并行 System.Threading.Tasks.Parallel 类

    一.并行概念 1.并行编程 在.NET 4中的并行编程是依赖Task Parallel Library(后面简称为TPL) 实现的.在TPL中,最基本的执行单元是task(中文可以理解为"任 ...

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

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

  4. 【读书笔记】.Net并行编程(三)---并行集合

    为了让共享的数组,集合能够被多线程更新,我们现在(.net4.0之后)可以使用并发集合来实现这个功能.而System.Collections和System.Collections.Generic命名空 ...

  5. Delphi XE7并行编程: 并行For循环

    从Delphi XE7开始,引入了全新的并行编程库用于简化并行编程,它位于System.Threading单元中. 下面是一个判断素数的简单例子:function IsPrime (N: Intege ...

  6. .Net多线程 并行编程(三)---并行集合

    为了让共享的数组,集合能够被多线程更新,我们现在(.net4.0之后)可以使用并发集合来实现这个功能. 而System.Collections和System.Collections.Generic命名 ...

  7. C#并行编程中的Parallel.Invoke

    一.基础知识 并行编程:并行编程是指软件开发的代码,它能在同一时间执行多个计算任务,提高执行效率和性能一种编程方式,属于多线程编程范畴.所以我们在设计过程中一般会将很多任务划分成若干个互相独立子任务, ...

  8. Parallel并行编程

    Parallel并行编程 Parallel并行编程可以让我们使用极致的使用CPU.并行编程与多线程编程不同,多线程编程无论怎样开启线程,也是在同一个CPU上切换时间片.而并行编程则是多CPU核心同时工 ...

  9. C#并行编程

    C#并行编程中的Parallel.Invoke 一.基础知识 并行编程:并行编程是指软件开发的代码,它能在同一时间执行多个计算任务,提高执行效率和性能一种编程方式,属于多线程编程范畴.所以我们在设计过 ...

随机推荐

  1. ural1989 单点更新+字符串hash

    正解是双哈希,不过一次哈希也能解决.. 然后某个数字就对应一个字符串,虽然有些不同串对应同一个数字,但是概率非常小,可以忽略不计.从左到右.从右到左进行两次hash,如果是回文串,那么对应的整数必定存 ...

  2. python3 + selenium 多iframe(框架)切换

    html演示: frame.html: <html> <head> <meta http-equiv="content-type" content=& ...

  3. MVC开发中的常见错误-07-“System.IO.DirectoryNotFoundException”类型的未经处理的异常在 mscorlib.dll 中发生

    “System.IO.DirectoryNotFoundException”类型的未经处理的异常在 mscorlib.dll 中发生 其他信息: 未能找到路径“F:\Users\home\Docume ...

  4. 《转》Pragma: no-cache 对性能的影响

    做了下go和java的http性能的简单比较服务端直接输出字符串使用JMeterwindows下  2000的并发,测试结果很出乎意料,go不会这么差吧 研究了半小时,原因如下tomcat的servl ...

  5. RabbitMQ(四): rabbitmq 的消息确认机制(事务+confirm)

    在 rabbitmq 中我们可以通过持久化数据解决 rabbitmq 服务器异常的数据丢失问题. 问题:生产者将消息发送出去之后,消息到底有没有到达 rabbitmq 服务器.默认情况下是不知道的. ...

  6. 几种常见SQL分页方式效率比较

    分页很重要,面试会遇到.不妨再回顾总结一下: 一:创建测试环境,(插入100万条数据大概耗时5分钟). create database DBTestuse DBTest 二:--创建测试表 creat ...

  7. bootstrap改变上传文件按钮样式,并显示已上传文件名

    参考博文: html中,文件上传时使用的<input type="file">的样式自定义 html中<input type="file"&g ...

  8. [转]Mysql 存储过程和函数区别

    http://blog.csdn.net/wangsifu2009/article/details/6725213 存储过程是用户定义的一系列sql语句的集合,涉及特定表或其它对象的任务,用户可以调用 ...

  9. python全栈开发day14--内置函数和匿名函数

  10. PopupWindow分享页面

    效果图 步骤: 1.布局中添加分享按钮 2.画出分享页面 3.设置分享页面animator进出动画,并在style.xml中配置 4.MainActivity中添加方法 *画出布局 主页面: < ...