C#停止線程的方法
更新時間:2015年08月20日 17:51:52 作者:我心依舊
這篇文章主要介紹了C#停止線程的方法,實例分析了C#正確停止線程的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#停止線程的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinFormApp { public partial class Form1 : Form { System.Threading.CancellationTokenSource cancel = new System.Threading.CancellationTokenSource(); System.Threading.Thread[] thread; int len = 2; public Form1() { InitializeComponent(); thread = new System.Threading.Thread[len]; } void RunThread() { ThreadInvoke.SetEventInvokeValue(richTextBox1, "即將開始運(yùn)行線程."); System.Threading.Thread t = null; for (int i = 0; i < len; i++) { t = new System.Threading.Thread(new System.Threading.ThreadStart(Sample)); t.Name = "thread_0" + i.ToString(); t.IsBackground = true; thread.SetValue(t, i); t.Start(); } } void Sample() { string name = System.Threading.Thread.CurrentThread.Name; ThreadInvoke.SetEventInvokeValue(richTextBox1, "正在運(yùn)行線程:" + name); while (true) { if (cancel.IsCancellationRequested) { ThreadInvoke.SetEventInvokeValue(richTextBox1, "線程:" + name + " 停止運(yùn)行..."); //線程被終止后回調(diào) cancel.Token.Register(delegate { ThreadInvoke.SetEventInvokeValue(richTextBox1, "線程:" + name + " 停止運(yùn)行之后的回調(diào)函數(shù)..."); }); break; } } } void ShowStatu() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (thread[i].IsAlive == true) { sb.AppendLine("線程:" + thread[i].Name.ToString() + " 還在運(yùn)行..."); } } if (sb.ToString() == "") { sb.AppendLine("線程已經(jīng)全部停止..."); } richTextBox1.Text += sb.ToString(); } /// <summary> /// 開始運(yùn)行線程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { RunThread(); } /// <summary> /// 顯示所有的線程狀態(tài) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { ShowStatu(); } /// <summary> /// 終止所有的線程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { cancel.Cancel(); } } }
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#上位機(jī)與三菱PLC通訊的實現(xiàn)步驟(圖文)
這篇文章主要介紹了C#上位機(jī)與三菱PLC通訊的實現(xiàn)步驟(圖文),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02C#開發(fā)Android百度地圖手機(jī)應(yīng)用程序(多地圖展示)
這篇文章主要介紹了C#開發(fā)Android百度地圖手機(jī)應(yīng)用程序(多地圖展示)的相關(guān)資料,需要的朋友可以參考下2016-02-02C#實現(xiàn)將Email地址轉(zhuǎn)成圖片顯示的方法
這篇文章主要介紹了C#實現(xiàn)將Email地址轉(zhuǎn)成圖片顯示的方法,涉及C#操作圖片的相關(guān)技巧,需要的朋友可以參考下2015-06-06精簡高效的C#網(wǎng)站優(yōu)化經(jīng)驗技巧總結(jié)
這篇文章主要為大家介紹了精簡高效的C#網(wǎng)站優(yōu)化經(jīng)驗技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04C#中的lock、Monitor、Mutex學(xué)習(xí)筆記
這篇文章主要介紹了C#中的lock、Monitor、Mutex學(xué)習(xí)筆記,本文講解的都是線程同步的一些知識,需要的朋友可以參考下2015-01-01