c# - 这个事件处理代码会导致内存泄漏吗?

标签 c# memory-leaks .net-3.5 garbage-collection

这是内存泄漏吗?

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;
}

最佳答案

这取决于 RemoteClient 类中的其他内容。如果没有要dispose的对象,则不会发生内存泄漏。如果有任何对象具有 IDisposable 内容,则需要继承 ÌDisposable` 并销毁这些对象。 我认为删除处理程序并退出循环对您来说也不是什么新鲜事。

因为客户端听起来像一个 Web 服务,所以了解一下所谓的异步线程可能很重要。 .NET: Do I need to keep a reference to WebClient while downloading asynchronously?

此外,如果整个事情变得更加复杂,检查对象状态也很重要。 Complex client server

关于c# - 这个事件处理代码会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7649745/

相关文章:

c# - 这个静态方法是线程安全的吗?

c# - 当相等比较器基于 OR 运算时,编写 GetHashCode() 的正确方法是什么?

c# - 从另一个项目访问 app.config 值

.net - 有没有办法静默或自动安装 .NET?

c# - 使用 LINQ 获取一个 List<> 中不在另一个 List<> 中的项目

c# - 在C#中使用正则表达式来匹配rtf格式的文本

c# - 错误 : This operation would create an incorrectly structured document

ios - 无法使用 Xcode Instruments 定位内存泄漏

c++ - 我的程序泄漏了 boost::shared_ptr 拥有的资源

java - GC 分配的堆空间为 2048 mb 后,堆内存未释放小于 1200 mb