C#内存泄漏循环 [英] c# memory leak in loop

查看:104
本文介绍了C#内存泄漏循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 public void DoPing(object state)
    {
        string host = state as string;
        m_lastPingResult = false;
        while (!m_pingThreadShouldStop.WaitOne(250))
        {


                Ping p = new Ping();
                try
                {

                    PingReply reply = p.Send(host, 3000);
                    if (reply.Status == IPStatus.Success)
                    {

                        m_lastPingResult = true;
                    }
                    else { m_lastPingResult = false; }

                }
                catch { }
                numping = numping + 1;
            }


    }

有人知道为什么这段代码会给我带来内存泄漏吗?我可以看到它是这段代码,因为将等待值更改为较小或较大的值会增加内存使用率.有谁知道如何解决吗?或如何查看导致它的代码的哪一部分?

Any idea why this code gives me a memory leak? I can see it's this code as changing the wait value to smaller or larger values increases the rate of the memory usage. Does any one have any idea how to resolve it? or how to see what part of the code is causing it?

推荐答案

在某些垃圾回收语言中,如果创建该对象的方法仍未退出,则存在不能收集该对象的限制.

In some garbage collected languages, there is a limitation that the object isn't collected if the method that created it still hasn't exited.

我相信.net可以在调试模式下以这种方式工作.引用本文;请注意粗体字.

I believe .net works this way in debug mode. Quoting from this article; note the bolded statement.

http://www .simple-talk.com/dotnet/.net-framework/understanding-garbage-collection-in-.net/

考虑当前正在运行的方法中的局部变量 成为GC的根.这些变量引用的对象始终可以 可以通过声明它们的方法立即访问,等等 他们必须保持周围.这些根的寿命取决于 程序的构建方式. 在调试版本中,本地变量持续存在 只要方法在堆栈上就可以.在发行版中,JIT 能够查看程序结构以得出最后一点 在执行过程中,该方法可以使用变量,并且 不再需要它时将丢弃它.这个策略不是 始终使用,可以关闭它,例如,通过运行该程序 在调试器中.

A local variable in a method that is currently running is considered to be a GC root. The objects referenced by these variables can always be accessed immediately by the method they are declared in, and so they must be kept around. The lifetime of these roots can depend on the way the program was built. In debug builds, a local variable lasts for as long as the method is on the stack. In release builds, the JIT is able to look at the program structure to work out the last point within the execution that a variable can be used by the method and will discard it when it is no longer required. This strategy isn’t always used and can be turned off, for example, by running the program in a debugger.

这篇关于C#内存泄漏循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆