开发者

Memory leak using System.Forms.Timer

Here is the simplified block of code:

private void timer1_Tick(object sender, EventArgs e开发者_如何转开发)
{
    using(Bitmap bmp = new Bitmap(48, 48))
    { }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜