欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#停止线程的方法

程序员文章站 2023-08-17 16:33:22
本文实例讲述了c#停止线程的方法。分享给大家供大家参考。具体实现方法如下: using system; using system.collections.gen...

本文实例讲述了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#程序设计有所帮助。