是否有一个事件时,垃圾收集发生在.NET呢? [英] Is there an event for when garbage collection occurs in .NET?

查看:118
本文介绍了是否有一个事件时,垃圾收集发生在.NET呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的放缓在我的ASP.NET网站,我似乎无法追查。我怀疑GC可能会被踢和阻止我的线程。要确信这将是很好的记录每次GC时确实发生了。

I've got a weird slowdown in my ASP.NET website that I cannot seem to track down. I'm suspecting that GC might be kicking in and halting my threads. To know for sure it would be nice to log every time when GC does occur.

我可以做一个虚拟对象,并做好记录在它的终结,但随后这将是一个一次性的解决方案,而在我的情况下,有几个这样的可解释暂停。

I could make a dummy object and do the logging in its finalizer, but that would then be a one-shot solution, while in my case there are several such inexplainable pauses.

任何想法?

补充:的环境是VS2008 / .NET 3.5 SP1。不,在垃圾收集通知不会做,因为他们是投票的方法,以及没有为并发的GC工作

Added: The environment is VS2008/.NET 3.5 SP1. And no, the Garbage Collection Notifications won't do because they are a method of polling, and don't work for a concurrent GC.

推荐答案

下面是一个简单的一招。它可能不是100%准确,但它可能就可以了。

Here's a simple trick. It might not be 100% accurate, but it will probably be good enough.

如果你能忍受定稿的通知,再有就是你可以用一个简单的方法。

If you can live with being notified of finalization, then there is a simple method you can use.

创建一个对象,不保持对它的引用。当对象被最终确定,你提高你的事件,然后构造另一个对象。不要将你的引用,这个对象要么,但它会活得完全够用集合进行,直到下一次。

Create an object, and don't keep a reference to it. When the object is finalized, you raise your event, and then construct another object. You don't keep a reference to this object either, but it will live until the next time a complete enough collection is performed.

下面是这样一个对象:

public class GCNotifier
{
    public static event EventHandler GarbageCollected;

    ~GCNotifier()
    {
        if (Environment.HasShutdownStarted)
            return;
        if (AppDomain.CurrentDomain.IsFinalizingForUnload())
            return;
        new GCNotifier();
        if (GarbageCollected != null)
            GarbageCollected(null, EventArgs.Empty);
    }

    public void Start()
    {
        GCNotifier();
    }
}

如果你愿意,你可以添加通过具有静态布尔字段,起价在下次重新启动定稿本身p $ pvents就停止对它的支持。

If you want, you can add support for stopping it by having a static boolean field which prevents it from restarting itself upon next finalization.

希望这是有一定的帮助。

Hope this is of some help.

这篇关于是否有一个事件时,垃圾收集发生在.NET呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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