創作內容

14 GP

C# Task Cancel 任務取消

作者:貓貓風 ฅ●ω●ฅ│2019-02-04 17:52:34│巴幣:28│人氣:3855
.












Task 和 Thread 一樣,都是屬於執行緒的一種,Task 和 Thread主要的差異為 Task在多執行緒

的狀態會自動按比例調整,排程,屬於多執行緒特化的一種物件,還資源許多狀態管理

低級別操作,優先全調度等功能

本篇主要是演示,如何在Task運行中進行取消的動作

在建立Task時傳入可隨時處發取消的Token ? 稱做 CancellationToken

並在執行取消命令時送出 Cacel指令,藉此取消 Task的動作

以下為實作程式碼 (此程式不能在Debug模式下執行)


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Threading;  
  10. using System.Threading.Tasks;  
  11.   
  12. namespace Task_Status  
  13. {  
  14.     public partial class Form1 : Form  
  15.     {  
  16.         public Form1()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.   
  21.         CancellationTokenSource cts = new CancellationTokenSource();  
  22.         CancellationToken cancelToken;  
  23.         Thread _monitor_task;  
  24.         Task<int> t;  
  25.         bool click = false;  
  26.   
  27.         private void Form1_Load(object sender, EventArgs e)  
  28.         {  
  29.             cancelToken = cts.Token;  
  30.             _monitor_task = new Thread(monitor_task);  
  31.             _monitor_task.Start();  
  32.   
  33.             //new task bind with cancel token  
  34.             //return result use int type  
  35.             t = new Task<int>(() => AddCancleByThrow(cancelToken), cancelToken);   
  36.             t.Start();  
  37.             t.ContinueWith(TaskEndedByCatch); //when task complete run this  
  38.               
  39.         }  
  40.   
  41.         void monitor_task()  
  42.         {  
  43.             while (true)  
  44.             {  
  45.                 this.Invoke(new Action(() => {  
  46.                 textBox3.Text = t.IsCanceled.ToString();  
  47.                 textBox4.Text = t.IsCompleted.ToString();  
  48.                 textBox5.Text = t.IsFaulted.ToString();  
  49.                 }));  
  50.                   
  51.                 // monitor is cancel ?  
  52.                 if (t.IsCanceled)  
  53.                 {  
  54.                     this.Invoke(new Action(() => {  
  55.                     textBox2.Text = "task Cancel";  
  56.                     }));  
  57.                     t.Dispose();  
  58.                    // t = null;  
  59.                       
  60.                 }  
  61.   
  62.                 Thread.Sleep(30);  
  63.             }  
  64.         }  
  65.   
  66.         void TaskEndedByCatch(Task<int> task) //task end do this  
  67.         {  
  68.             try  
  69.             {  
  70.                   
  71.                 this.Invoke(new Action(() => {  
  72.                 // get run result  
  73.                 textBox2.Text = "task Complete: result = "+task.Result ;  
  74.                 button1.Text = "New task";  
  75.                 }));  
  76.                 click = !click;  
  77.                 t.Dispose();  
  78.   
  79.             }  
  80.             catch (AggregateException e)  
  81.             {  
  82.                MessageBox.Show(e.ToString());  
  83.             }  
  84.         }  
  85.   
  86.         int AddCancleByThrow(CancellationToken ct) // running task   
  87.         {  
  88.             int result = 0;  
  89.   
  90.             this.Invoke(new Action(() =>{  
  91.             textBox2.Text = "new Task Running";  
  92.              }));  
  93.   
  94.                 while (result < 5)  
  95.                 {  
  96.                     if (ct.IsCancellationRequested)  
  97.                     {  
  98.                         ct.ThrowIfCancellationRequested();   
  99.                     }  
  100.                     result++;  
  101.                    this.Invoke(new Action(() =>{  
  102.   
  103.                         textBox1.Text = result.ToString();  
  104.                    }));  
  105.                     Thread.Sleep(1000);  
  106.                 }  
  107.   
  108.             return result;  
  109.         }  
  110.   
  111.         private void button1_Click(object sender, EventArgs e)  
  112.         {  
  113.             //wait press to stop  
  114.             if (!click)  
  115.             {  
  116.                 cts.Cancel();  
  117.                 button1.Text = "New task";  
  118.                 click = !click;  
  119.             }  
  120.             else  
  121.             {  
  122.                 button1.Text = "Cancel";  
  123.                 click = !click;  
  124.                 textBox2.Text = "new Task Running";  
  125.                 // when start new task  
  126.                 cts = new CancellationTokenSource();  
  127.                 cancelToken = cts.Token;  
  128.                 if (t != null)  
  129.                 {  
  130.                     t = new Task<int>
  131.                     (() => AddCancleByThrow(cancelToken), cancelToken);  
  132.                     t.Start();  
  133.                     t.ContinueWith(TaskEndedByCatch);  
  134.                 }   
  135.             }  
  136.         }  
  137.   
  138.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  139.         {  
  140.             _monitor_task.Abort();  
  141.         }  
  142.     }  
  143. }  
執行結果

執行Task中  未被取消  未完成  皆為 false




執行完成 Complete = true



重新執行新 Task  並在執行中 處發取消事件

Cancel = true  在取消同時也會觸發完成 Complete = true




實際運行畫面

引用網址:https://home.gamer.com.tw/TrackBack.php?sn=4283186
All rights reserved. 版權所有,保留一切權利

相關創作

同標籤作品搜尋:涼涼風|C#

留言共 2 篇留言

嚮鄉紅
新年快樂

02-04 18:12

貓貓風 ฅ●ω●ฅ
新年快樂唷02-04 21:56
小刀
新年快樂~

02-04 19:39

貓貓風 ฅ●ω●ฅ
刀姊新年快樂02-04 21:56
我要留言提醒:您尚未登入,請先登入再留言

14喜歡★s1234567 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:C# Random Co... 後一篇:C# 可輸入數值彈跳視...

追蹤私訊切換新版閱覽

作品資料夾

Lobster0627全體巴友
大家可以多多來我的YT頻道看看哦(*´∀`)~♥https://www.youtube.com/@lobstersandwich看更多我要大聲說7小時前


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】