首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GC.SuppressFinalize有保证吗?

GC.SuppressFinalize有保证吗?
EN

Stack Overflow用户
提问于 2009-04-27 08:33:11
回答 5查看 4K关注 0票数 6

我在实践中观察到,GC.SuppressFinalize并不总是抑制对终结器的调用。可能是终结器被称为“无论如何”。因此,我想知道GC.SuppressFinalize是否具有请求的性质,而不是系统的保证?

更多信息

如果需要,下面的信息可能有助于为问题提供更多的上下文。

GC.SuppressFinalize文档摘要确实声明了这是一个请求:

请求系统不调用指定对象的终结器。

我不知道这是一个随意使用的词,还是真正用来描述运行时的行为。

下面的SingletonScope类是从施内尔项目中提取的,它是基于一个伊恩·格里菲斯的原创创意的,但它更一般化,我观察到了这一点。这样做的目的是在调试构建中检测是否调用了Dispose方法。如果没有,终结器最终会启动,人们可以提出警告。如果调用Dispose,则GC.SuppressFinalize应防止终结器触发。不幸的是,这些警告似乎是以某种方式发出的,但并不是确定性的。也就是说,他们不会对每一次跑步开火。

代码语言:javascript
复制
#region License, Terms and Author(s)
//
// Schnell - Wiki widgets
// Copyright (c) 2007 Atif Aziz. All rights reserved.
//
//  Author(s):
//      Atif Aziz, http://www.raboof.com
//
// This library is free software; you can redistribute it and/or modify it 
// under the terms of the GNU Lesser General Public License as published by 
// the Free Software Foundation; either version 2.1 of the License, or (at 
// your option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, 
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
//
#endregion

namespace WikiPad
{
    #region Imports

    using System;
    using System.Diagnostics;

    #endregion

    //
    // NOTE: To use SingletonScope and ISingletonScopeHelper with value 
    // types, use Nullable<T>. For example, if the type of value to scope
    // is ThreadPriority then use ISingletonScopeHelper<ThreadPriority?>
    // and SingletonScope<ThreadPriority?>.
    //

    //
    // In debug builds, this type is defined as a class so a finalizer
    // can be used to detect an undisposed scope.
    //

    /// <summary>
    /// Designed to change a singleton and scope that change. After exiting
    /// the scope, the singleton is restored to its value prior to entering
    /// the scope.
    /// </summary>

    #if !DEBUG
    internal struct SingletonScope<T, H> 
    #else
    internal sealed class SingletonScope<T, H> 
    #endif
        : IDisposable 
        where H : ISingletonScopeHelper<T>, new()
    {
        private T _old;

        public SingletonScope(T temp)
        {
            _old = Helper.Install(temp);
        }

        private static H Helper
        {
            get { return new H(); }
        }

        public void Dispose()
        {
            //
            // First, transfer fields to stack then nuke the fields.
            //

            var old = _old;
            _old = default(T);

            //
            // Shazam! Restore the old value.
            //

            Helper.Restore(old);

            #if DEBUG
            GC.SuppressFinalize(this); // Only when defined as a class!
            #endif
        }

        #if DEBUG

        //
        // This finalizer is used to detect an undisposed scope. This will
        // only indicate that the scope was not disposed but (unfortunately)
        // not which one and where since GC will probably collect much later
        // than it should have been disposed.
        //

        ~SingletonScope()
        {
            Debug.Fail("Scope for " + typeof(T).FullName + " not disposed!");
        }

        #endif
    }
}

http://gist.github.com/102424上有一个完整的工作示例,附带编译说明,但请注意,到目前为止,这个问题还不能确定地重现。

EN

回答 5

Stack Overflow用户

发布于 2009-04-27 08:48:55

您可能看到的一个奇怪的问题是,即使实例方法仍在运行,终结器仍然可以运行,只要该实例方法以后不使用任何变量。因此,在示例代码中,Dispose方法在第一行之后不使用任何实例变量。即使Dispose仍在运行,实例也可以最后确定。

如果在GC.KeepAlive(this)方法的末尾插入对Dispose的调用,您可能会发现问题消失了。

克里斯·布鲁姆( Chris )有一个关于这个的博客帖子,我认为在某个地方还有另外一个.

票数 4
EN

Stack Overflow用户

发布于 2009-04-27 09:14:04

我总是使用这种设计模式来实现IDisposable接口。(这是微软的建议),对我来说,GC.SuppressFinalize总是有一个保证的性质!

代码语言:javascript
复制
using System;
using System.ComponentModel;

//The following example demonstrates how to use the GC.SuppressFinalize method in a resource class to prevent the clean-up code for the object from being called twice.

public class DisposeExample
{
    // A class that implements IDisposable.
    // By implementing IDisposable, you are announcing that 
    // instances of this type allocate scarce resources.
    public class MyResource : IDisposable
    {
        // Pointer to an external unmanaged resource.
        private IntPtr handle;
        // Other managed resource this class uses.
        private readonly Component component = new Component();
        // Track whether Dispose has been called.
        private bool disposed;

        // The class constructor.
        public MyResource(IntPtr handle)
        {
            this.handle = handle;
        }

        // Implement IDisposable.
        // Do not make this method virtual.
        // A derived class should not be able to override this method.
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue 
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed.
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!disposed)
            {
                // If disposing equals true, dispose all managed 
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    component.Dispose();
                }

                // Call the appropriate methods to clean up 
                // unmanaged resources here.
                // If disposing is false, 
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;
            }
            disposed = true;
        }

        // Use interop to call the method necessary  
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code.
        // This destructor will run only if the Dispose method 
        // does not get called.
        // It gives your base class the opportunity to finalize.
        // Do not provide destructors in types derived from this class.
        ~MyResource()
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of
            // readability and maintainability.
            Dispose(false);
        }
    }

    public static void Main()
    {
        // Insert code here to create
        // and use a MyResource object.
    }
}

来源:MSDN: GC.SuppressFinalize方法

票数 4
EN

Stack Overflow用户

发布于 2009-07-16 04:02:43

我在终结器中抛出一个InvalidOperationException,这样很容易找到没有正确处理的类型。当调用GC.SuppressFinalize的地方调用Dispose()时,我永远不会得到异常。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/792660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档