TPL——等待Task

等待特定时间:

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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一尺丈量

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值