当垃圾回收发生时,是否有任何事件告诉应用程序? [英] Are there any events that tell an application when garbage collection has occurred?

查看:78
本文介绍了当垃圾回收发生时,是否有任何事件告诉应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种了解垃圾收集的方法.无论是何时开始,完成或进行中.我真的只需要一些与集合本身相关的事件即可.

I am trying to find a way to know about garbage collection. Either, when it has started, finished or is in process. I really just need some event connected to the collection itself (I think).

我的问题是我有一个WeakEventManager(从头开始编写),并且我有一些删除方法和删除的WeakReferences不再有效(WeakReferences在字典中).

My issue is that I have a WeakEventManager (written from scratch) and I have cleanup methods that delete and WeakReferences that are no longer alive (WeakReferences are in a Dictionary).

问题是我必须知道何时该进行清理".收集器正在执行其操作时清理它会很不错.即使是在垃圾回收之后,至少下一个回收也会删除这些旧对象.

The issue is that I have to know when it is time to "clean up". It would be nice to cleanup when the collector is doing its thing. Even if it is after the garbage collection, at least the next collection will remove these old objects.

推荐答案

这是我用来登录到SmartInspect的类,该类已发生GC.您应该可以轻松更改此类的功能.

Here's the class I used to log to SmartInspect that GC has occured. You should easily be able to change what this class does.

要开始使用,只需调用GCLog.Register();.

To get it started, simply call GCLog.Register();.

#region File Header
// This file Copyright © 2007 Lasse Vågsæther Karlsen, All rights reserved.
//
// $Id: GCLog.cs 135 2008-05-28 11:28:37Z lassevk $
#endregion

#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Gurock.SmartInspect;

#endregion

namespace PresentationMode
{
    /// <summary>
    /// This class is used to get a running log of the number of garbage collections that occur,
    /// when running with logging.
    /// </summary>
    public sealed class GCLog
    {
        #region Construction & Destruction

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="GCLog"/> is reclaimed by garbage collection.
        /// </summary>
        ~GCLog()
        {
            SiAuto.Main.LogMessage("GARBAGE COLLECTED");
            if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && !Environment.HasShutdownStarted)
                new GCLog();
        }

        #endregion

        #region Public Static Methods

        /// <summary>
        /// Registers this instance.
        /// </summary>
        public static void Register()
        {
#if DEBUG
            if (SiAuto.Si.Enabled)
                new GCLog();
#endif
        }

        #endregion
    }
}

这篇关于当垃圾回收发生时,是否有任何事件告诉应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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