What#39;s the purpose of GC.SuppressFinalize(this) in Dispose() method?(Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?)
问题描述
我有以下代码:
public void Dispose()
{
if (_instance != null)
{
_instance = null;
// Call GC.SupressFinalize to take this object off the finalization
// queue and prevent finalization code for this object from
// executing a second time.
GC.SuppressFinalize(this);
}
}
虽然有一条注释解释了与 GC 相关的调用的目的,但我仍然不明白为什么会出现.
Although there is a comment that explains purpose of that GC-related call, I still don't understand why it's there.
当所有实例不存在时,对象是否注定要进行垃圾回收,例如在 using 块中使用时?
Isn't object destined for garbage collection once all instances cease from existence, like, when used in using block?
这将发挥重要作用的用例场景是什么?
What's the use case scenario where this would play important role?
推荐答案
在实现 dispose 模式时,您还可以向调用 Dispose() 的类添加终结器.这是为了确保 Dispose() always 被调用,即使客户端忘记调用它.
When implementing the dispose pattern you might also add a finalizer to your class that calls Dispose(). This is to make sure that Dispose() always gets called, even if a client forgets to call it.
为了防止 dispose 方法运行两次(以防对象已经被释放),您添加 GC.SuppressFinalize(this);.该文档提供了一个示例:
To prevent the dispose method from running twice (in case the object already has been disposed) you add GC.SuppressFinalize(this);. The documentation provides a sample:
class MyResource : IDisposable
{
[...]
// This destructor will run only if the Dispose method
// does not get called.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
resource.Cleanup()
}
disposed = true;
}
}
这篇关于Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
