在c#中,thread
类的abort()
方法用于终止线程。如果未完成中止操作,它会引发threadabortexception
异常。
using system;
using system.threading;
public class mythread
{
public void thread1()
{
for (int i = 0; i < 10; i++)
{
console.writeline(i);
thread.sleep(200);
}
}
}
public class threadexample
{
public static void main()
{
console.writeline("start of main");
mythread mt = new mythread();
thread t1 = new thread(new threadstart(mt.thread1));
thread t2 = new thread(new threadstart(mt.thread1));
t1.start();
t2.start();
try
{
t1.abort();
t2.abort();
}
catch (threadabortexception tae)
{
console.writeline(tae.tostring());
}
console.writeline("end of main");
}
}
执行上面示例代码,得到以下结果(输出是不可预测的,因为线程可能处于运行状态。) -
start of main
0
end of main