这个事件处理代码会导致内存泄漏吗?
这是内存泄漏吗?
private void Process()
{
for (; ; )
{
// local variable
RemoteClient remoteClient = new RemoteClient(..);
// subscription without unsubscription
remoteClient.BadClient += new EventHandler(remoteClient_BadClient);
}
..
}
public class RemoteClient
{
...
public event EventHandler BadClient;
}
Is this a memory leak?
private void Process()
{
for (; ; )
{
// local variable
RemoteClient remoteClient = new RemoteClient(..);
// subscription without unsubscription
remoteClient.BadClient += new EventHandler(remoteClient_BadClient);
}
..
}
public class RemoteClient
{
...
public event EventHandler BadClient;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于 RemoteClient 类中的其他内容。如果没有要
dispose
的对象,则不会发生内存泄漏。如果有任何对象具有IDisposable
内容,则需要继承 ÌDisposable` 并销毁这些对象。我认为删除处理程序并退出循环对您来说也不是什么新鲜事。
因为客户端听起来像一个 Web 服务,所以了解一下所谓的异步线程可能很重要。
.NET:我需要吗在异步下载时保留对 WebClient 的引用?
另外,如果整个事情变得更加复杂,检查对象状态也很重要。
It depends on what else is in the RemoteClient class. If there is NO object to
dispose
this is no memory leak. If there are any objects withIDisposable
content, you need to inherit ÌDisposable` and destroy those objects.Also its not new to you to remove the handler and exit loop I think.
Because client sounds like an webservice it could be important to have a look to called asynchron Threads.
.NET: Do I need to keep a reference to WebClient while downloading asynchronously?
Also if the whole stuff becomes to be more complex, it is important to check the objects state.
如果您退出
for
循环,这不是内存泄漏。每个remoteClient
将保存对remoteClient_BadClient
委托的引用,但remoteClient
本身将适用于每次迭代后的垃圾回收(如果您不存储对remoteClient
其他地方!)。收集remoteClient
还将处理对remoteClient_BadClient
委托的引用,该委托也将允许收集它。This is not a memory leak in case if you will exit your
for
loop. EachremoteClient
will hold reference to aremoteClient_BadClient
delegate butremoteClient
itself will be applicable for garbage collection after each iteration (if you do not store reference toremoteClient
somewhere else!). CollectingremoteClient
will also dispose the reference toremoteClient_BadClient
delegate which will allow collecting it also.不,除非你处于无限循环中。
No, unless you are in an infinite loop.