你不应该依靠你的Dispose
方法将被调用。
你可以用WeakReference
包装你的类实例。一旦引用被垃圾收集,线程应该停止工作。
class MyClass : IDisposable
{
class CancellationSignal
{
WeakReference _reference;
public bool IsWorking { get { return _working && _reference.IsAlive; } }
volatile bool _working;
public CancellationSignal(WeakReference reference)
{
if (reference == null) throw new ArgumentNullException("reference");
_reference = reference;
}
public void Signal()
{
_working = false;
}
}
CancellationSignal _cancellationSignal;
public MyClass()
{
_cancellationSignal = new CancellationSignal(new WeakReference(this));
Thread t = new Thread(Worker);
t.Start(_cancellationSignal);
}
static void Worker(object state)
{
var s = (CancellationSignal)state;
while (s.IsWorking)
{
//...
}
}
public void Dispose()
{
_cancellationSignal.Signal();
}
}
我个人倾向于避免使用终结,但我还是不得不说,另一种解决办法是调用终结Signal
(然后你可以删除WeakReference
东西):
~MyClass()
{
_cancellationSignal.Signal();
}
注意_working
是声明为不稳定。您也可以使用ManualResetEventSlim
或甚至CancellationToken
。
在这两种方法(WeakReference
和终结),你必须避免将this
参考主题(因为它会阻止垃圾回收你的类的实例),因此我添加了一个CancellationSignal
类和标注Worker
为静态。
对我来说似乎很好。除非你想至少让'working'变量'volatile'。否则,即使在处理“MyClass”后,实际上您的线程也可能永远不会结束。 – sstan