Some people says that Thread.Abort is evil.But the following is what the msdn says.
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx
using System;
using System.Threading;
using System.Security.Permissions;
public class ThreadWork {
public static void DoWork() {
try {
for(int i=0; i<100; i++) {
Console.WriteLine("Thread - working.");
Thread.Sleep(100);
}
}
catch(ThreadAbortException e) {
Console.WriteLine("Thread - caught ThreadAbortException - resetting.");
Console.WriteLine("Exception message: {0}", e.Message);
Thread.ResetAbort();
}
Console.WriteLine("Thread - still alive and working.");
Thread.Sleep(1000);
Console.WriteLine("Thread - finished working.");
}
}
class ThreadAbortTest {
public static void Main() {
ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();
Thread.Sleep(100);
Console.WriteLine("Main - aborting my thread.");
myThread.Abort();
myThread.Join();
Console.WriteLine("Main ending.");
}
}
本文通过一个示例展示了如何使用 .NET 中 Thread.Abort 方法来终止线程,并讨论了这种方法可能带来的问题及如何处理 ThreadAbortException。需要注意的是,由于 Thread.Abort 存在风险,建议探索更安全的替代方案。
1万+

被折叠的 条评论
为什么被折叠?



