设置图标属性时出现 NotifyIcon 内存泄漏?
我正在尝试设置 notificationicon 控件的图标,但每次更改图标属性时,即使我释放图标,我也可以看到应用程序的内存增加。
这是我的代码(c#):
public void CheckNotifyIcon(bool visible)
{
if (notifyIcon.Icon != null)
notifyIcon.Icon.Dispose();
notifyIcon.Icon = visible
? new Icon(Pic1, new Size(32, 32))
: new Icon(Pic2, new Size(32, 32));
notifyIcon.Visible = visible;
}
我做错了什么?
谢谢你!
I am trying to set the icon of the notifyicon control but everytime i change the icon property i can see my memory for my application increase even though i release the icon.
This is my code (c#) :
public void CheckNotifyIcon(bool visible)
{
if (notifyIcon.Icon != null)
notifyIcon.Icon.Dispose();
notifyIcon.Icon = visible
? new Icon(Pic1, new Size(32, 32))
: new Icon(Pic2, new Size(32, 32));
notifyIcon.Visible = visible;
}
What have i done wrong?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不会创建一个
NotifyIcon
并不断将其Icon
属性切换为Icon
的临时实例,而是创建两个NotifyIcon
> 控件,并适当地显示/隐藏它们。这样,Icon
实例在表单的生命周期内仅创建一次,而不是不断地被处置和重新创建(并且它们的最终处置由 WinForms 设计者编写的管道代码来管理)为你)。虽然这不会告诉您内存泄漏发生在哪里,但它应该首先避免它。Instead of having a single
NotifyIcon
and continually switching it'sIcon
property to temporary instances ofIcon
, I would create twoNotifyIcon
controls, and show/hide them appropriately. This way theIcon
instances are created only once for the lifetime of the form, rather than continuously being disposed and re-created (and their eventual disposal is managed for you by the plumbing code which the WinForms designer writes for you). Whilst this won't tell you where the memory leak is occurring, it should avoid it in the first place.如何启动 Redgate 的 ANTS Memory Profiler 来查找找出原因?
此外,我建议不要捕获并处理异常以获取更多信息。
How about firing up Redgate's ANTS Memory Profiler to find out the cause?
In addition, I'd suggest to not catch and eat the exception to get more information.
首先,你发布的代码没有泄露。您处理掉图标,当然 .net 垃圾收集器不会泄漏。
在对您提出的问题的评论中:
这就是你的问题的根源。 Windows 内存管理极其复杂,任务管理器并不是诊断泄漏的合适工具。
将其与 .net 垃圾收集器结合起来,情况会更加混乱。垃圾收集器完全可以自由地尽可能长时间地保留所有分配的内存,只要这不会影响系统的其余部分。
检测 .net 中的内存泄漏是一项复杂的任务,需要专用工具。
First of all, there is no leak in the code you publish. You dispose of the icon and of course the .net garbage collector does not leak.
In a comment to the question you state:
This is the source of your problem. Windows memory management is exceedingly complex, and task manager is not an appropriate tool to diagnose leaks.
Combine this with the .net garbage collector and the picture is even muddier. The garbage collector is perfectly at liberty to hold on to all allocated memory for as long as it can, so long as that does not impact on the rest of the system.
Detecting memory leaks in .net is a complex task and requires dedicated tools.