IDisposable-如何正确实施此

时间:2020-09-30 13:37:36

标签: c# .net

我的课程如下:

public class WowRedirectionDisabler : IDisposable
{
    private IntPtr _oldValue;
    private bool _isDisposed;
        
    public WowRedirectionDisabler ()
    {
        if (!Environment.Is64BitOperatingSystem)
            throw new NotSupportedException("OperatingSystem must be 64 bits");

        if (!NativeMethods.Wow64DisableWow64FsRedirection(out _oldValue))
            throw new ExternalException("Unable to disable Wow64 Redirection");
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_isDisposed) return;

        if (!NativeMethods.Wow64RevertWow64FsRedirection(_oldValue))
            throw new ExternalException("Unable to revert Wow64 Redirection");
    }

    ~WowRedirectionDisabler ()
    {
        Dispose(false);
    }
}

我可以保证_oldValue在终结器需要运行时会一直存在吗?如果没有,该如何正确实施?

0 个答案:

没有答案