Mat*_*ley 3 .net c# multithreading
今天我正在玩我的一个项目并找到一个有趣的小片段,给定以下模式,你可以安全地清理一个线程,即使它被迫提前关闭.我的项目是一个网络服务器,它为每个客户端生成一个新线程.我发现这对于从远程端提前终止是有用的,但也可以从本地端(我可以.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();
}
}
Run Code Online (Sandbox Code Playgroud)
作为参考,没有try/finally块,线程就像人们期望的那样死掉.
Jon*_*eet 14
除非整个应用程序崩溃,否则完全中止另一个线程只是一个坏主意.将程序置于未知状态太容易了.中止你自己的线程偶尔会有用 - ThreadAbortException例如,如果你想过早地结束响应,ASP.NET会抛出一个- 但它并不是一个非常好的设计.
安全清理线程应该是相互的 - 应该有一些共享标志请求线程关闭.线程应定期检查该标志并适当退出.
| 归档时间: |
|
| 查看次数: |
2206 次 |
| 最近记录: |