使用Dispose()方法 [英] Using Dispose() method

查看:144
本文介绍了使用Dispose()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在发布模式下向代码中添加 timer.Dispose()时会多次看到 Hello字样。没有 timer.Dispose(),我只会看到 Hello一次。谢谢。

Why I see "Hello" words many times when I add timer.Dispose() to my code in release mode. Without timer.Dispose() I see "Hello" once. Thanks.

using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Method(object state)
        {
            Console.WriteLine(state);
            GC.Collect();
        }

        static void Main()
        {
            var timer = new Timer(Method, "Hello", 0, 200);

            Console.ReadLine();
            timer.Dispose();
        }
    }
}


推荐答案

您一次看到它是因为垃圾收集器已经收集了计时器对象。

You see it once because the garbage collector has collected the timer object.

因为没有更多的引用被认为是活动的垃圾收集器可以免费这样做。

Since there are no more references to it that is considered "live" the garbage collector is free to do so.

在发布模式下,当没有连接调试器时,JITter会积累关于在方法中使用局部变量的知识。一旦不再使用变量,如果该方法当前在该点以下执行,则不再将其视为根。这样,垃圾收集器可以收集计时器对象。但是,在这样做之前,它必须完成对象的定义,这将破坏底层的计时器对象并使其停止执行。

In release mode, and when no debugger is attached, the JITter builds up knowledge of where local variables are used in a method. Once a variable is no longer used, it is no longer considered to be a root if the method is currently executing below that point. As such, the garbage collector can collect the timer object. However, before it can do so it must finalize the object, which destroys the underlying timer object and stops it from executing.

在调试版本中,所有局部变量的范围被人为地扩展为整个方法,因此,即使在程序不再实际上要求该变量存在的情况下,如果在方法中放置断点也可以检查变量。

In debug builds, the scope of all local variables are artificially extended to be the entire method, so that if you place a breakpoint in the method you can inspect variables, even if the program would no longer actually require that variable to exist.

添加了对dispose的调用后,您延长了变量的生存期,从而阻止了垃圾收集器收集计时器对象。

When you added the call to dispose, you extended the lifetime of the variable, and thus prevented the garbage collector from collecting your timer object.

由于您引发了在计时器事件处理程序方法中进行垃圾回收,在这种情况下,您可以有效地销毁计时器。通过添加对Dispose的调用来延长变量的生存期时,垃圾收集器仍会作为计时器事件处理程序的一部分运行,但是它仍无法收集计时器,因此它会继续运行。

Since you provoke a garbage collection in the timer event handler method, you effectively destroy the timer yourself in this case. When you extended the lifetime of the variable by adding in the call to Dispose, the garbage collector still runs as part of your timer event handler, but it cannot yet collect the timer, so it keeps running.

汉斯·帕桑特(Hans Passant)在此处留下的答案比我上面的微薄尝试更好地说明了这一点:

The answer left here by Hans Passant describes this much better than my meager attempt above:

了解.NET中的垃圾收集

这篇关于使用Dispose()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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