线程终止
(1)Thread.Abort()用法

.
private Thread t1;
private void button1_Click(object obj,EventArgs args)
{
t1 = new Thread(Doloop);
t1.IsBackground = true;
t1.Start();
}
private void Doloop()
{MethodInvoker startMethod = delegate { this.label1.Text = "starting
"; };MethodInvoker attachMethod = delegate { this.label1.Text = "haha!"; };

if(this.label1.InvokeRequired){
for(int i = 0; i < 1000000; i++){
this.label1.Invoke(startMethod);
Thread.Sleep(0); //指示应挂起此线程以使其他等待线程能够执行.}
}
}
private void button2_Click(Object obj,EventArgs arg)
{
t1.Abort();
t1.Join();
this.label1.Text = "Thread is Destroy";
}



对于上述代码,当button2执行t1.Abort()时,在Doloop()函数体中将引发ThreadAbortException异常,t1线程被中止。注意,此时由于在button2的Click事件中,使用t1.Join()函数,故在捕获异常时,不能对catch或者finally语句块进行任何操作。原因在于,如果在捕获异常时,catch或finally语句块中存在任何操作,被中止的线程将在catch或者finally语句块的末尾再次引发,这样将导致调用线程(主界面线程)将被无限期阻断。
(2)Thread.ResetAbort()用法

.
private Thread t1;
private void button1_Click(object obj,EventArgs args)
{
t1 = new Thread(Doloop);
t1.IsBackground = true;
t1.Start();
}
private void Doloop()
{MethodInvoker startMethod = delegate { this.label1.Text = "starting
"; };MethodInvoker attachMethod = delegate { this.label1.Text = "haha!"; };
try{
if(this.label1.InvokeRequired)
{
for(int i = 0; i < 1000000; i++){
this.label1.Invoke(startMethod);
Thread.Sleep(0); //指示应挂起此线程以使其他等待线程能够执行.}
}
}
catch
{
Thread.ResetAbort();
}
this.label1.Invoke(attachMethod);
}
private void button2_Click(Object obj,EventArgs arg)
{
t1.Abort();
}



当使用Thread.ResetAbort函数时,将取消线程要中止的请求,此时,在button2中,Click事件的Abort()函数将不能中止线程t1。
浙公网安备 33010602011771号