国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#停止線程的方法

2020-01-24 01:31:22
字體:
來源:轉載
供稿:網友

本文實例講述了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#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 溧水县| 秦安县| 海丰县| 慈溪市| 玉田县| 确山县| 景泰县| 东莞市| 呈贡县| 会同县| 剑河县| 长岭县| 石棉县| 墨江| 江华| 富顺县| 左云县| 平乡县| 三亚市| 昔阳县| 独山县| 图木舒克市| 郧西县| 沽源县| 洪湖市| 博爱县| 宁远县| 长治县| 都匀市| 青铜峡市| 南汇区| 塔河县| 盖州市| 桦川县| 彭泽县| 秦安县| 五指山市| 铜梁县| 石首市| 龙门县| 盐城市|