关闭

TPL——取消一个Task

标签: C#TPLTask多线程
202人阅读 评论(0) 收藏 举报
分类:

取消一个Task

using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_07 {
class Listing_07 {
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource
= new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create the task
Task task = new Task(() => {
for (int i = 0; i < int.MaxValue; i++) {
if (token.IsCancellationRequested) {
Console.WriteLine("Task cancel detected");
throw new OperationCanceledException(token);
} else {
Console.WriteLine("Int value {0}", i);
}
}
}, token);
// wait for input before we start the task
Console.WriteLine("Press enter to start task");
Console.WriteLine("Press enter again to cancel task");
Console.ReadLine();
// start the task
task.Start();
// read a line from the console.
Console.ReadLine();
// cancel the task
Console.WriteLine("Cancelling task");
tokenSource.Cancel();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}

监控Task的取消1:使用委托

using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_08 {
class Listing_08 {
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource
= new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create the task
Task task = new Task(() => {
for (int i = 0; i < int.MaxValue; i++) {
if (token.IsCancellationRequested) {
Console.WriteLine("Task cancel detected");
throw new OperationCanceledException(token);
} else {
Console.WriteLine("Int value {0}", i);
}
}
}, token);
// register a cancellation delegate
token.Register(() => {
Console.WriteLine(">>>>>> Delegate Invoked\n");
});
// wait for input before we start the task
Console.WriteLine("Press enter to start task");
Console.WriteLine("Press enter again to cancel task");
Console.ReadLine();
// start the task
task.Start();
// read a line from the console.
Console.ReadLine();
// cancel the task
Console.WriteLine("Cancelling task");
tokenSource.Cancel();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}
监控Task的取消2:WaitOne()

using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_09 {
class Listing_09 {
static void Main(string[] args) {
// create the cancellation token source
CancellationTokenSource tokenSource
= new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create the task
Task task1 = new Task(() => {
for (int i = 0; i < int.MaxValue; i++) {
if (token.IsCancellationRequested) {
Console.WriteLine("Task cancel detected");
throw new OperationCanceledException(token);
} else {
Console.WriteLine("Int value {0}", i);
}
}
}, token);
// create a second task that will use the wait handle
Task task2 = new Task(() => {
// wait on the handle
token.WaitHandle.WaitOne();
// write out a message
Console.WriteLine(">>>>> Wait handle released");
});
// wait for input before we start the task
Console.WriteLine("Press enter to start task");
Console.WriteLine("Press enter again to cancel task");
Console.ReadLine();
// start the tasks
task1.Start();
task2.Start();
// read a line from the console.
Console.ReadLine();
// cancel the task
Console.WriteLine("Cancelling task");
tokenSource.Cancel();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}
取消几个Task

using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_10 {
class Listing_10 {
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 < int.MaxValue; i++) {
token.ThrowIfCancellationRequested();
Console.WriteLine("Task 1 - Int value {0}", i);
}
}, token);
Task task2 = new Task(() => {
for (int i = 0; i < int.MaxValue; i++) {
token.ThrowIfCancellationRequested();
Console.WriteLine("Task 2 - Int value {0}", i);
}
}, token);
// wait for input before we start the tasks
Console.WriteLine("Press enter to start tasks");
Console.WriteLine("Press enter again to cancel tasks");
Console.ReadLine();
// start the tasks
task1.Start();
task2.Start();
// read a line from the console.
Console.ReadLine();
// cancel the task
Console.WriteLine("Cancelling tasks");
tokenSource.Cancel();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}
复合Token

using System;
using System.Threading;
using System.Threading.Tasks;
namespace Listing_11 {
class Listing_11 {
static void Main(string[] args) {
// create the cancellation token sources
CancellationTokenSource tokenSource1 = new CancellationTokenSource();
CancellationTokenSource tokenSource2 = new CancellationTokenSource();
CancellationTokenSource tokenSource3 = new CancellationTokenSource();
// create a composite token source using multiple tokens
CancellationTokenSource compositeSource =
CancellationTokenSource.CreateLinkedTokenSource(
tokenSource1.Token, tokenSource2.Token, tokenSource3.Token);
// create a cancellable task using the composite token
Task task = new Task(() => {
// wait until the token has been cancelled
compositeSource.Token.WaitHandle.WaitOne();
// throw a cancellation exception
throw new OperationCanceledException(compositeSource.Token);
}, compositeSource.Token);
// start the task
task.Start();
// cancel one of the original tokens
tokenSource2.Cancel();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}
一个Task是否已经被取消?

You can determine if a Task has been cancelled by checking the IsCancelled property, which will return true if the Task was cancelled.

如果一个Task已经被取消,IsCancelled属性将返回true.






0
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

TPL——开始一个Task

创建Tasks的四个方式: using System; using System.Threading.Tasks; namespace Listing_02 { class Listing_02 { ...
  • u010155023
  • u010155023
  • 2016-08-29 16:46
  • 176

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

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

C#中可取消的Task

1、需求 我们知道task是并行计算的,比如说主线程在某个时刻由于某种原因要取消某个task的执行,我们能做到吗? 当然我们可以做到。 在4.0中给我们提供一个“取消标记”叫做Cancellat...
  • hxfhq1314
  • hxfhq1314
  • 2016-09-24 19:26
  • 8693

TPL——等待Task

等待特定时间: CancallationToken.WaitHandle.WaitOne() Thread.Sleep() Thread.SpinWait()前两个函数将在等待的时候被投入睡眠,而Th...
  • u010155023
  • u010155023
  • 2016-08-29 17:27
  • 204

C# 中通过CancellationTokenSource实现对超时任务的取消

我们在多线程中通常使用一个bool IsExit类似的代码来控制是否线程的运行与终止,其实使用CancellationTokenSource来进行控制更为好用,下面我们将介绍CancellationT...
  • CNHK1225
  • CNHK1225
  • 2017-02-26 21:40
  • 1234

C# Task的用法

C# Task 的用法 其实Task跟线程池ThreadPool的功能类似,不过写起来更为简单,直观。代码更简洁了,使用Task来进行操作。可以跟线程一样可以轻松的对执行的方法进行控制。 ...
  • tieshuxianrezhang
  • tieshuxianrezhang
  • 2017-02-09 11:19
  • 2187

使用Task的一些知识优化了一下同事的多线程协作取消的一串代码

最近在看一个同事的代码,代码的本意是在main方法中开启10个线程,用这10个线程来处理一批业务逻辑,在某一时刻当你命令console退出的时候,这个 时候不是立即让console退出,而是...
  • king_zxy
  • king_zxy
  • 2017-03-13 18:46
  • 417

extjs中通过tpl实现带图标的ComboBox

extjs中通过tpl实现带图标的ComboBox   (2010-12-20 19:34:52) 转载▼ 标签:  extjs   图标   c...
  • evilcry2012
  • evilcry2012
  • 2016-03-02 11:38
  • 1079

[笔记][Java7并发编程实战手册]4.9-4.10在执行器中控制任务的完成和取消任务FutureTask

[笔记][Java7并发编程实战手册]系列目录简介在前面都是把需要执行的Runnable或则Callable提交给线程池,让线程池来管理任务的生命周期。在本章会学习:怎么取消任务的运行,在任务运行中,...
  • mr_zhuqiang
  • mr_zhuqiang
  • 2015-09-01 22:36
  • 784

今天再给大家带点html5前端开发的干货模板“text/tpl”怎么用 script template怎么用

text/tpl 顾名思义就是模板,其实和C++模板函数类似的作用,就是利用他生成一个HMTL内容,然后append或者替换html里面 有什么好处,假如后端返回来的数据都是一样的,但是需要生...
  • xyx33
  • xyx33
  • 2016-11-05 10:07
  • 2521
    个人资料
    • 访问:72498次
    • 积分:1108
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:2篇
    • 译文:1篇
    • 评论:9条
    最新评论