终结和处置 [英] Finalizers and Dispose

查看:122
本文介绍了终结和处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为的BackgroundWorker 一类具有线程持续运行。要关闭这个线程关闭,命名实例变量停止需要可真正



为确保上课的时候​​被使用做线程被释放,我已经添加了的IDisposable 和终结调用的Dispose()。假设停止=真确实导致此线程退出,这是sippet正确的?它的优良调用的Dispose 从一个终结,对吧?



终结,应该总是调用处置如果对象继承的IDisposable ,对吧?

  ///<总结> 
///强制后台线程退出。
///< /总结>
公共无效的Dispose()
{
锁(this.locker)
{
this.stop = TRUE;
}
}

〜BackgroundWorker的()
{
this.Dispose();
}


解决方案

您的代码是好的,但在终结锁定有点吓人,我会避开它 - 如果你得到一个僵局......我不是100%肯定会发生什么,但它不会是一件好事。但是,如果是安全的这应该不是一个问题。大多。垃圾收集的内部是痛苦的,我希望你永远不会看到他们;)



正如马克Gravell指出,挥发性布尔将让你摆脱锁定,这将缓解这个问题。如果你可以实现这个变化。



nedruod的代码放在里面,如果(处置)检查,这是完全错误的分配 - 线程是一个非托管资源,必须加以制止即使没有明确的处理。您的代码是好的,我只是指出,你不应该采取在代码片段给出的建议。



是的,你总是应该从调用Dispose()如果实现IDisposable模式终结。完整的IDisposable模式比你有什么大一点,但你并不总是需要它 - 它只是提供了两个额外的可能性:




  1. 检测是否的Dispose()被调用或终结正在执行(你不能碰任何托管资源的终结,对象外正在定稿);

  2. 让子类重写的Dispose ()方法。


I've got a class named BackgroundWorker that has a thread constantly running. To turn this thread off, an instance variable named stop to needs to be true.

To make sure the thread is freed when the class is done being used, I've added IDisposable and a finalizer that invokes Dispose(). Assuming that stop = true does indeed cause this thread to exit, is this sippet correct? It's fine to invoke Dispose from a finalizer, right?

Finalizers should always call Dispose if the object inherits IDisposable, right?

/// <summary>
/// Force the background thread to exit.
/// </summary>
public void Dispose()
{
    lock (this.locker)
    {
        this.stop = true;
    }
}

~BackgroundWorker()
{
    this.Dispose();
}

解决方案

Your code is fine, although locking in a finalizer is somewhat "scary" and I would avoid it - if you get a deadlock... I am not 100% certain what would happen but it would not be good. However, if you are safe this should not be a problem. Mostly. The internals of garbage collection are painful and I hope you never have to see them ;)

As Marc Gravell points out, a volatile bool would allow you to get rid of the lock, which would mitigate this issue. Implement this change if you can.

nedruod's code puts the assignment inside the if (disposing) check, which is completely wrong - the thread is an unmanaged resource and must be stopped even if not explicitly disposing. Your code is fine, I am just pointing out that you should not take the advice given in that code snippet.

Yes, you almost always should call Dispose() from the finalizer if implementing the IDisposable pattern. The full IDisposable pattern is a bit bigger than what you have but you do not always need it - it merely provides two extra possibilities:

  1. detecting whether Dispose() was called or the finalizer is executing (you are not allowed to touch any managed resources in the finalizer, outside of the object being finalized);
  2. enabling subclasses to override the Dispose() method.

这篇关于终结和处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆