c# - SafeWaitHandle 与 SafeFileHandle c#

标签 c# .net base-class-library

我正在阅读 .net 框架源代码: https://referencesource.microsoft.com

我发现 BCL 包含两个完全相同的类:SafeWaitHandleSafeFileHandle。他们都有完全相同的代码!

来自引用源(SafeFileHandle):

[System.Security.SecurityCritical]  // auto-generated_required
public sealed class SafeFileHandle: SafeHandleZeroOrMinusOneIsInvalid {

    private SafeFileHandle() : base(true) 
    {
    }

    public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
        SetHandle(preexistingHandle);
    }

    [System.Security.SecurityCritical]
    [ResourceExposure(ResourceScope.Machine)]
    [ResourceConsumption(ResourceScope.Machine)]
    override protected bool ReleaseHandle()
    {
        return Win32Native.CloseHandle(handle);
    }
}

来自引用源(SafeWaitHandle):

[System.Security.SecurityCritical]  // auto-generated_required
    public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        // Called by P/Invoke marshaler
        private SafeWaitHandle() : base(true)
        {
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle)
        {
            SetHandle(existingHandle);
        }

        [System.Security.SecurityCritical]
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        override protected bool ReleaseHandle()
        {
            return Win32Native.CloseHandle(handle);
        }
    }

我看到构造函数对 IntPtr 参数和 SafeWaitHandle 的注释有不同的名称,试图告诉我一些事情。但我无法理解,因为代码是相同的,而且据我所知,这些类应该提供相同的行为。

有人知道为什么微软的人创建了这些 equals 类吗?为什么我应该更喜欢一门课而不是另一门课,在什么情况下?

最佳答案

区别在于语义。大多数句柄都是相似的——只是对某些资源的引用(通常只是一个指针)。但是,区分它们很有用。如果您有一些接受 SafeFileHandle 的 api - 它不会接受 SafeWaitHandle(或存在的其他类型的句柄),这可能会防止一些细微的错误。如果它改为接受一些抽象的 Handle - 那么有人可以在那里传递任何句柄,不代表对文件的引用。因此,不同类型的句柄由不同的类表示(即使具有相同的实现)+ C# 类型安全有利于防止将一种类型的句柄传递到需要另一种类型的句柄的地方。

关于c# - SafeWaitHandle 与 SafeFileHandle c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252330/

相关文章:

c# - 希望使用C#中的dll编译基本程序

c# - 尝试通过 FindObjectOfType 获取集合时找不到对象集合

C# 处理动态字体大小的方法

collections - 为什么 HashSet<T> 不实现 IReadOnlyCollection<T>?

c# - Linq 的 Enumerable.Count 方法检查 ICollection<> 但不检查 IReadOnlyCollection<>

c# - 在C#中将音频流添加到视频流

c# - 命名使用 Log4net 生成的文件

c# - 跟踪方法执行时间

c# - 我为什么要使用 Microsoft Expression Blend?

c# - 为什么 math.Ceiling(double a) 不直接返回 int?