处置不被调用
我在这里看到了一些关于在对象超出范围时处理对象的方法的帖子,但我尝试过的似乎都不起作用。
我创建了一个loadingscreen 类,因此我在表单的xxx_load 函数中声明该对象。我希望当对象超出范围时自动处理该对象,以便自动隐藏加载屏幕。
这是我的加载类
public class Loader : IDisposable
{
public Loader()
{
Form.Loadscreen();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
Form.UnloadScreen();
}
}
这是我在代码中使用它的方式。
using (Loader loader = new Loader())
{
//... do some loading processing
loader.Dispose();
}
即使我可以验证 loader.Dispose() 正在被调用,但有时仍然存在对象没有被释放的情况。
有什么建议吗?
I have seen a few posts on here on ways to get an object disposed when it goes out of scope, but nothing I have tried seems to work.
I have a loadingscreen class I created, so I declare the object in a form's xxx_load function. I want the object to be disposed automatically when it goes out of scope so the hiding of the loading screen will be taken care of automatically.
Here is my loading class
public class Loader : IDisposable
{
public Loader()
{
Form.Loadscreen();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
Form.UnloadScreen();
}
}
Here is how I am using it in my code.
using (Loader loader = new Loader())
{
//... do some loading processing
loader.Dispose();
}
even though I can verify that loader.Dispose() is being called, there are still times where the object is not being disposed.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您不需要显式调用
loader.Dispose()
:这就是使用using
块背后的全部要点(它调用Dispose
> 自动)。其次,“对象没有被释放”是什么意思,因为正在调用 Dispose(而且它不可能不被调用;使用确保了这一点) 。
First of all, you do not need to call
loader.Dispose()
explicitly: that's the whole point behind having ausing
block (it callsDispose
automatically).Second, what do you mean "the object is not being disposed", since
Dispose
is being called (and there's no way it would not be called; theusing
ensures that).无论如何只使用
Anyway use just
除了 IDisposable 和 using 语句负责处理对象的答案之外:
如果您正在观察任务管理器的内存占用情况,
Dispose()
不会使分配的内存量收缩。一个常见的误解是,您的应用程序内存占用量会在分配和释放内存的同时收缩和扩展。这不是真的。虽然分配大块内存可能会使占用空间立即增加,但释放却不会这样。如果您仍然确信资源没有被释放,您可以尝试析构函数。
Aside from the answers that say IDisposable and the using statement take care of disposing your object:
If you are watching taskmanager for the memory footprint,
Dispose()
will not make the amount of allocated memory shrink. It is a common misconception that your application memory footprint shrinks and expands at the exact moment memory is allocated and deallocated. This isn't true. While allocating large chunks of memory may make the footprint increase instantly, deallocation doesn't work that way.If you are still convinced resources are not being let go, you could try a destructor.