关闭

TPL——等待Task

标签: TPLC#Task取消线程多线程
312人阅读 评论(0) 收藏 举报
分类:

等待特定时间:

CancallationToken.WaitHandle.WaitOne()
Thread.Sleep()
Thread.SpinWait()
前两个函数将在等待的时候被投入睡眠,而Thread.SpinWait()却会使线程处于一个高强度的运行状态。



等待线程的完成:

Waiting for a Single Task
You can wait for a single Task to complete by calling theWait() instance method. The calling method will not return until theTask instance has completed, been cancelled or thrown an exception.


using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_16 {
class Listing_16 {
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create and start the first task, which we will let run fully
Task task = createTask(token);
task.Start();
// wait for the task
Console.WriteLine("Waiting for task to complete.");
task.Wait();
Console.WriteLine("Task Completed.");
// create and start another task
task = createTask(token);
task.Start();
Console.WriteLine("Waiting 2 secs for task to complete.");
bool completed = task.Wait(2000);
Console.WriteLine("Wait ended - task completed: {0}", completed);
// create and start another task
task = createTask(token);
task.Start();
Console.WriteLine("Waiting 2 secs for task to complete.");
completed = task.Wait(2000, token);
Console.WriteLine("Wait ended - task completed: {0} task cancelled {1}",
completed, task.IsCanceled);
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
static Task createTask(CancellationToken token) {
return new Task(() => {
for (int i = 0; i < 5; i++) {
// check for task cancellation
token.ThrowIfCancellationRequested();
// print out a message
Console.WriteLine("Task - Int value {0}", i);
// put the task to sleep for 1 second
token.WaitHandle.WaitOne(1000);
}
}, token);
}
}
}

Waiting for Several Tasks
You can wait for a number of tasks to complete by using the staticTask.WaitAll()method. This method will not return until all of the tasks passed as arguments have completed, been cancelled, or thrown an exception. 
TipWhen using this method, aTask is considered complete if it has finished its workload, been cancelled, or thrown an exception. If one or more of your tasks has thrown an exception, theWaitAll()method will throw an exception. See the “Handling Exceptions” section in this chapter for details.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_17 {
class Listing_17 {
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create the tasks
Task task1 = new Task(() => {
for (int i = 0; i < 5; i++) {
// check for task cancellation
token.ThrowIfCancellationRequested();
// print out a message
Console.WriteLine("Task 1 - Int value {0}", i);
// put the task to sleep for 1 second
token.WaitHandle.WaitOne(1000);
}
Console.WriteLine("Task 1 complete");
}, token);
Task task2 = new Task(() => {
Console.WriteLine("Task 2 complete");
}, token);
// start the tasks
task1.Start();
task2.Start();
// wait for the tasks
Console.WriteLine("Waiting for tasks to complete.");
Task.WaitAll(task1, task2);
Console.WriteLine("Tasks Completed.");
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}


Waiting for One of Many Tasks
The Task.WaitAny() method waits for one of a set of tasks to complete, and this method has a number of overloads, all of which take aTask array. 
TipWhen using this method, aTask is considered complete if it has finished its workload, been cancelled, or thrown an exception. If one or more of your tasks has thrown an exception, theWaitAny()method will throw an exception.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_18 {
class Listing_18 {
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create the tasks
Task task1 = new Task(() => {
for (int i = 0; i < 5; i++) {
// check for task cancellation
token.ThrowIfCancellationRequested();
// print out a message
Console.WriteLine("Task 1 - Int value {0}", i);
// put the task to sleep for 1 second
token.WaitHandle.WaitOne(1000);
}
Console.WriteLine("Task 1 complete");
}, token);
Task task2 = new Task(() => {
Console.WriteLine("Task 2 complete");
}, token);
// start the tasks
task1.Start();
task2.Start();
// wait for the tasks
Console.WriteLine("Waiting for tasks to complete.");
int taskIndex = Task.WaitAny(task1, task2);
Console.WriteLine("Task Completed. Index: {0}", taskIndex);
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}



0
0
查看评论

【C#】43. TPL基础——Task初步

从这篇文章开始,我想直接进入关于Task的一些内容,有时间再回顾Threadpool的相关内容。 我一开始接触Task就觉得他和Thread很像,都是开新的线程。但是两者有很多区别,其中比较明显的是:Task创建的是线程池任务,而Thread默认创建的是前台任务。     同...
  • huiwuhuiwu
  • huiwuhuiwu
  • 2016-12-11 20:56
  • 1148

Task Parallel Library ( TPL)学习

原文:http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n 上码: using System; using System.Linq; using System.Threading; using System.Thr...
  • Joyhen
  • Joyhen
  • 2015-08-13 13:54
  • 829

TPL 和传统 .NET 异步编程一

TPL即任务并行库,是.NET Framework 4版本中的新鲜物,是System.Threading 和 System.Threading.Tasks 命名空间中的一组公共类型和 API。TPL 的目的在于简化向应用程序中添加并行性和并发性的过程,从而提高开发人员的工作效率。 ...
  • minyskirt
  • minyskirt
  • 2010-05-28 17:47
  • 3485

22 C# 第十八章 TPL 并行编程

C# TPL(Task Parallel Library)和PLINQ(Parallel LINQ) 并行编程 是.Net4 为多线程编程引入的新的API。 一: Task 线程的基本使用 关于Action委托: 它是 .Net 定义的一种委托类型。 public delegate vo...
  • wangzhiyu1980
  • wangzhiyu1980
  • 2013-08-12 09:24
  • 4834

TPL——开始一个Task

创建Tasks的四个方式: using System; using System.Threading.Tasks; namespace Listing_02 { class Listing_02 { static void Main(string[] args) { // use an Action...
  • u010155023
  • u010155023
  • 2016-08-29 16:46
  • 279

TPL——取消一个Task

取消一个Task using System; using System.Threading; using System.Threading.Tasks; namespace Listing_07 { class Listing_07 { static void Main(string[] args)...
  • u010155023
  • u010155023
  • 2016-08-29 17:05
  • 307

c# Task多线程并行任务中等待所有线程都执行完成

C#多线程中如何等待所有线程的任务都执行完成呢?在.net 4.0以4.0+中,有Task.WaitAll(params Task[] tasks)方法来等待所有Task[],而不需要更多的操作。按照微软官方的文档,我写了一个实例来调试和说明: using System; using Syst...
  • zhaoyipei1977
  • zhaoyipei1977
  • 2017-01-10 00:51
  • 5289

C# Winform 基于Task的异步与延时执行

一、Task的机制Task位于命名空间System.Threading.Tasks中,是.NET 4.0加入的新模块,其实现机制大致类似于线程池ThreadPool,不过对于ThreadPool来说Task的优势是很明显的:ThreadPool的实现机制:(一对多)1、应用程序拥有一个用于存放委托的...
  • qq992817263
  • qq992817263
  • 2017-02-22 14:38
  • 2630

Activiti 学习笔记11:接收活动(receiveTask,即等待活动)

接收任务是一个简单任务,它会等待对应消息的到达。 当前,官方只实现了这个任务的java语义。 当流程达到接收任务,流程状态会保存到数据库中。 在任务创建后,意味着流程会进入等待状态 , 直到引擎接收了一个特定的消息 , 这会触发流程穿过接收任务继续执行。一、流程图二、演示代码package ji...
  • xunzaosiyecao
  • xunzaosiyecao
  • 2016-09-11 11:28
  • 1830

Ext.Net 1.x_Ext.Net.TaskManager模拟进度条

一直很想做一个登陆时候的进度条 上图先: 吧   <ext:Task TaskID="Task1" ...
  • david_520042
  • david_520042
  • 2011-01-07 16:29
  • 2521
    个人资料
    • 访问:78531次
    • 积分:1162
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:2篇
    • 译文:1篇
    • 评论:10条
    最新评论