【发布时间】:2009-02-28 05:57:31
【问题描述】:
我今天在玩我的一个项目,发现了一个有趣的小sn-p,鉴于以下模式,您可以安全地清理线程,即使它被强制提前关闭。我的项目是一个网络服务器,它为每个客户端生成一个新线程。我发现这对于从远程端提早终止很有用,但也适用于本地端(我可以从我的处理代码中调用.Abort())。
您对此是否有任何问题,或者您对任何寻求类似方法的人有什么建议?
测试用例如下:
using System;
using System.Threading;
class Program
{
static Thread t1 = new Thread(thread1);
static Thread t2 = new Thread(thread2);
public static void Main(string[] args)
{
t1.Start();
t2.Start();
t1.Join();
}
public static void thread1() {
try {
// Do our work here, for this test just look busy.
while(true) {
Thread.Sleep(100);
}
} finally {
Console.WriteLine("We're exiting thread1 cleanly.\n");
// Do any cleanup that might be needed here.
}
}
public static void thread2() {
Thread.Sleep(500);
t1.Abort();
}
}
作为参考,如果没有 try/finally 块,线程就会像预期的那样死掉。
【问题讨论】:
标签: c# .net multithreading