Task 开始 停止
Posted 很久很久以前
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Task 开始 停止相关的知识,希望对你有一定的参考价值。
注意点:需要将每个线程的 MemoryCacheManager 保存,这里我保存在缓存中,需要取消时根据缓存key值取出 MemoryCacheManager
//开始Task1 private void button1_Click(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false;//winform运行跨线程 ICacheManager cacheManager = new MemoryCacheManager(); var cts1 = new CancellationTokenSource(); CancellationToken ct1 = cts1.Token; Task.Factory.StartNew(() => { while (true) { Thread.Sleep(500); listView1.Items.Add("AA当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (ct1.IsCancellationRequested) { // another thread decided to cancel listView1.Items.Add("task1 canceled"); cacheManager.Remove("cts1"); break; } } }, ct1); if (!cacheManager.IsSet("cts1")) { cacheManager.Set("cts1", cts1, 20); } } //开始Task2 private void button2_Click(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false;//winform运行跨线程 ICacheManager cacheManager = new MemoryCacheManager(); var cts2 = new CancellationTokenSource(); CancellationToken ct2 = cts2.Token; Task.Factory.StartNew(() => { while (true) { Thread.Sleep(500); listView1.Items.Add("BB当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (ct2.IsCancellationRequested) { // another thread decided to cancel listView1.Items.Add("task1 canceled"); cacheManager.Remove("cts2"); break; } } }, ct2); if (!cacheManager.IsSet("cts2")) { cacheManager.Set("cts2", cts2, 20); } } //停止Task1 private void button3_Click(object sender, EventArgs e) { ICacheManager cacheManager = new MemoryCacheManager(); var cts = cacheManager.Get<CancellationTokenSource>("cts1"); cts.Cancel(); } //停止Task2 private void button4_Click(object sender, EventArgs e) { ICacheManager cacheManager = new MemoryCacheManager(); var cts = cacheManager.Get<CancellationTokenSource>("cts2"); cts.Cancel(); }
以上是关于Task 开始 停止的主要内容,如果未能解决你的问题,请参考以下文章
Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题
为啥我的 C# 代码在回调到 C++ COM 时会停止,直到 Task.Wait/Thread.Join?