使用 System.Forms.Timer 发生内存泄漏

发布于 2024-09-14 16:12:17 字数 150 浏览 1 评论 0原文

这是简化的代码块:

private void timer1_Tick(object sender, EventArgs e)
{
    using(Bitmap bmp = new Bitmap(48, 48))
    { }
}

Here is the simplified block of code:

private void timer1_Tick(object sender, EventArgs e)
{
    using(Bitmap bmp = new Bitmap(48, 48))
    { }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风不识月 2024-09-21 16:12:17

由于问题中的信息有限,我只会对问题的内容做出一般性的反应。

您在每个计时器滴答声上创建一个小的位图。您使用using。这意味着代码被包装在 try/finally 块中。 finally 块将调用 bmp.Dispose() 来处理位图。但是,这并不意味着所有托管资源都会立即清理。仅当不存在对位图或其任何引用的引用时,才会在下一个垃圾收集周期中清除该内存。

要查明是否确实存在内存泄漏,请删除所有其他代码并创建一个仅包含上述代码和一些初始化代码的简单项目。将其放在表单上并向该表单添加一个按钮。单击该按钮时,执行 GC.Collect(),这将清除所有可释放的托管资源。如果这不能清理您的资源,则说明您存在资源泄漏,您应该发布缩小项目的代码。

注意:如果在 using 块内,您使用其他非托管资源而不添加新的 using 块,则这些资源不会被自动处置掉。在公开 IDiposable 的每个类周围包裹一个 using 块。

Because there's limited information in the question, I'll only react in general terms on what seems to be the question.

You create a small Bitmap on each timer tick. You use using. That means that the code is wrapped in a try/finally block. The finally block will call bmp.Dispose(), which disposes the bitmap. However, that does not mean that all managed resources are immediately cleaned up. This is only cleaned up with the next garbage collection cycle, and then, only when no references to the bitmap, or any of its references, exists.

To find out whether you really have a memory leak, remove all other code and create a simple project with just the above code and a bit of initialization code. Place it on a form and add a button to that form. When you click the button, do a GC.Collect(), which will clear all freeable managed resources. If that doesn't clean up your resources, you have a resource leak and you should post the minified project's code.

Note: if, inside the using-block, you use other unmanaged resources without adding a new using-block, then these will not be automatically disposed off. Wrap a using-block around each class that exposes IDiposable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文