C#停止线程的方法
本文实例讲述了C#停止线程的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
namespaceWinFormApp
{
publicpartialclassForm1:Form
{
System.Threading.CancellationTokenSourcecancel=newSystem.Threading.CancellationTokenSource();
System.Threading.Thread[]thread;
intlen=2;
publicForm1()
{
InitializeComponent();
thread=newSystem.Threading.Thread[len];
}
voidRunThread()
{
ThreadInvoke.SetEventInvokeValue(richTextBox1,"即将开始运行线程.");
System.Threading.Threadt=null;
for(inti=0;i<len;i++)
{
t=newSystem.Threading.Thread(newSystem.Threading.ThreadStart(Sample));
t.Name="thread_0"+i.ToString();
t.IsBackground=true;
thread.SetValue(t,i);
t.Start();
}
}
voidSample()
{
stringname=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;
}
}
}
voidShowStatu()
{
StringBuildersb=newStringBuilder();
for(inti=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>
///<paramname="sender"></param>
///<paramname="e"></param>
privatevoidbutton1_Click(objectsender,EventArgse)
{
RunThread();
}
///<summary>
///显示所有的线程状态
///</summary>
///<paramname="sender"></param>
///<paramname="e"></param>
privatevoidbutton2_Click(objectsender,EventArgse)
{
ShowStatu();
}
///<summary>
///终止所有的线程
///</summary>
///<paramname="sender"></param>
///<paramname="e"></param>
privatevoidbutton3_Click(objectsender,EventArgse)
{
cancel.Cancel();
}
}
}
希望本文所述对大家的C#程序设计有所帮助。