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

问题描述

我的ASP.NET网站有一个奇怪的放缓,我似乎无法追踪。我怀疑GC可能正在踢入和停止我的线程。要知道,当GC确实发生时,记录日志是很好的。



我可以做一个虚拟对象,并在其终结器中进行日志记录,作为一个单一的解决方案,而在我的情况下,有几个这样无法逾越的停顿。



任何想法?



已添加:环境为VS2008 / .NET 3.5 SP1。不,将不会,因为它们是方法的轮询,并不适用于并发GC。

解决方案

这是一个简单的技巧。它可能不是100%准确的,但它可能会够好。



如果您可以通过最终确定通知,那么您可以使用一种简单的方法。



创建一个对象,不要保留对它的引用。当对象被定义时,你提出你的事件,然后构造另一个对象。你也不会保留对这个对象的引用,但是直到下一次执行完整的集合才会生效。



这是一个对象:

  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()
{
new GCNotifier();
}
}

如果你愿意,你可以添加支持来停止它通过一个静态布尔字段阻止它在下次完成时重新启动。



希望这有一些帮助。


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.

Any ideas?

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.

解决方案

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.

Here's such an object:

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()
    {
        new GCNotifier();
    }
}

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中发生垃圾收集时是否有事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:20