C#停滯線程的辦法。本站提示廣大學習愛好者:(C#停滯線程的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#停滯線程的辦法正文
本文實例講述了C#停滯線程的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
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, "行將開端運轉線程."); 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, "正在運轉線程:" + name); while (true) { if (cancel.IsCancellationRequested) { ThreadInvoke.SetEventInvokeValue(richTextBox1, "線程:" + name + " 停滯運轉..."); //線程被終止後回調 cancel.Token.Register(delegate { ThreadInvoke.SetEventInvokeValue(richTextBox1, "線程:" + name + " 停滯運轉以後的回調函數..."); }); 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() + " 還在運轉..."); } } if (sb.ToString() == "") { sb.AppendLine("線程曾經全體停滯..."); } richTextBox1.Text += sb.ToString(); } /// <summary> /// 開端運轉線程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { RunThread(); } /// <summary> /// 顯示一切的線程狀況 /// </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#法式設計有所贊助。