欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#停止線(xiàn)程的方法

 更新時(shí)間:2015年08月20日 17:51:52   作者:我心依舊  
這篇文章主要介紹了C#停止線(xiàn)程的方法,實(shí)例分析了C#正確停止線(xiàn)程的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#停止線(xiàn)程的方法。分享給大家供大家參考。具體實(shí)現(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, "即將開(kāi)始運(yùn)行線(xià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)行線(xiàn)程:" + name);
   while (true)
   {
    if (cancel.IsCancellationRequested)
    {
     ThreadInvoke.SetEventInvokeValue(richTextBox1, "線(xiàn)程:" + name + " 停止運(yùn)行...");
     //線(xiàn)程被終止后回調(diào)
     cancel.Token.Register(delegate
     {
      ThreadInvoke.SetEventInvokeValue(richTextBox1, "線(xiàn)程:" + 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("線(xiàn)程:" + thread[i].Name.ToString() + " 還在運(yùn)行...");
    }
   }
   if (sb.ToString() == "")
   {
    sb.AppendLine("線(xiàn)程已經(jīng)全部停止...");
   }
   richTextBox1.Text += sb.ToString();
  }
  /// <summary>
  /// 開(kāi)始運(yùn)行線(xiàn)程
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void button1_Click(object sender, EventArgs e)
  {
   RunThread();
  }
  /// <summary>
  /// 顯示所有的線(xiàn)程狀態(tài)
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void button2_Click(object sender, EventArgs e)
  {
   ShowStatu();
  }
  /// <summary>
  /// 終止所有的線(xiàn)程
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void button3_Click(object sender, EventArgs e)
  {
   cancel.Cancel();
  }
 }
}

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論