gpt4 book ai didi

c# - 可以在一个对象上多次调用Dispose()导致崩溃吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:50 27 4
gpt4 key购买 nike

我正在调查应用程序中的偶发性崩溃,但仍不确定是什么原因造成的。当我想关闭包含VB 6.0或VC 6.0文本控件的MDI表单时,有时会发生这种情况-它的C#包装为Interop。在查看代码时,我注意到我有一些类似这样的代码:

 private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing) //Disposing of everything: managed and unmanaged resources.
{
moTextEditor.Dispose(); --here
moTextEditor.Dispose(); --here
}

// Deal with our own & whatever other unmanaged resources (this used to be done in the finalizer, above)
SetLockedFields(false);

disposed = true;
}
}

因此注意到moTextEditor.Dispose();线重复两次?你怎么看?这可能是问题吗?

最佳答案

IDisposable interfaceDispose文档专门指出:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.



如果对象正确实现了 IDisposable,那么这应该不是问题。

话虽这么说,并不是 IDisposable的所有实现都遵循规则。我个人会说该对象有一个错误,如果多次调用 Dispose有问题,应予以纠正。

关于c# - 可以在一个对象上多次调用Dispose()导致崩溃吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13480965/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com