【发布时间】:2012-06-27 19:26:43
【问题描述】:
我有一个 Windows 服务,它连续运行并创建一些线程来做一些工作。我想确保这些线程被妥善处理(完成后收集垃圾。
但是,我还希望能够定期检查它们是否还活着,如果存在则终止它们。不过,我知道我不能保留对它们的任何引用,因为那样它们就不会被垃圾回收。
是否有替代方法来检查用户定义线程的存在/状态?我在想也许像下面这样使用WeakReference:(我现在不能完全测试,或者我自己测试一下)
List<WeakReference> weakReferences;
Thread myThread = new Thread(() => Foo());
WeakReference wr = new WeakReference(myThread);
weakReferences.Add(wr); //adds a reference to the thread but still allows it to be garbage collected
myThread.Start();
myThread = null; //get rid of reference so thread can be garbage collected
然后在我的 onTimeElapsed 事件开始时(每 5 分钟运行一次):
foreach(WeakReference wr in weakReferences)
{
Thread target = wr.Target as Thread; //not sure if this cast is really possible
if(target.IsAlive && otherLogic)
{
target.Abort();
{
}
但我不确定 WeakReference 究竟是如何工作的。有关如何正确执行此操作的任何想法?
【问题讨论】:
-
确保线程被清理的最简单方法就是确保它们的工作最终终止(成功或其他)。我很好奇在什么情况下会产生一个线程并且你想在它工作完成之前清理它。
-
无论如何,中止线程是一个非常糟糕的主意。这通常会奏效,但您在这里安装了定时炸弹。
标签: c# multithreading garbage-collection weak-references