| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Runtime.InteropServices; |
| | | 7 | | using System.Threading; |
| | | 8 | | |
| | | 9 | | namespace Microsoft.Win32.SafeHandles |
| | | 10 | | { |
| | | 11 | | /// <summary>Provides a cache for special instances of SafeHandles.</summary> |
| | | 12 | | /// <typeparam name="T">Specifies the type of SafeHandle.</typeparam> |
| | | 13 | | internal static class SafeHandleCache<T> where T : SafeHandle |
| | | 14 | | { |
| | | 15 | | private static T? s_invalidHandle; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Gets a cached, invalid handle. As the instance is cached, it should either never be Disposed |
| | | 19 | | /// or it should override <see cref="SafeHandle.Dispose(bool)"/> to prevent disposal when the |
| | | 20 | | /// instance represents an invalid handle: <see cref="System.Runtime.InteropServices.SafeHandle.IsInvalid"/> ret |
| | | 21 | | /// </summary> |
| | | 22 | | internal static T GetInvalidHandle(Func<T> invalidHandleFactory) |
| | | 23 | | { |
| | | 24 | | return s_invalidHandle ?? CreateInvalidHandle(invalidHandleFactory); |
| | | 25 | | |
| | | 26 | | static T CreateInvalidHandle(Func<T> invalidHandleFactory) |
| | | 27 | | { |
| | | 28 | | T newHandle = invalidHandleFactory(); |
| | | 29 | | T? currentHandle = Interlocked.CompareExchange(ref s_invalidHandle, newHandle, null); |
| | | 30 | | |
| | | 31 | | if (currentHandle == null) |
| | | 32 | | { |
| | | 33 | | GC.SuppressFinalize(newHandle); |
| | | 34 | | currentHandle = newHandle; |
| | | 35 | | } |
| | | 36 | | else |
| | | 37 | | { |
| | | 38 | | newHandle.Dispose(); |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | Debug.Assert(currentHandle.IsInvalid); |
| | | 42 | | return currentHandle; |
| | | 43 | | } |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <summary>Gets whether the specified handle is invalid handle.</summary> |
| | | 47 | | /// <param name="handle">The handle to compare.</param> |
| | | 48 | | /// <returns>true if <paramref name="handle"/> is invalid handle; otherwise, false.</returns> |
| | | 49 | | internal static bool IsCachedInvalidHandle(SafeHandle handle) |
| | 0 | 50 | | { |
| | 0 | 51 | | Debug.Assert(handle != null); |
| | 0 | 52 | | bool isCachedInvalidHandle = ReferenceEquals(handle, s_invalidHandle); |
| | 0 | 53 | | Debug.Assert(!isCachedInvalidHandle || handle.IsInvalid, "The cached invalid handle must still be invalid.") |
| | 0 | 54 | | return isCachedInvalidHandle; |
| | 0 | 55 | | } |
| | | 56 | | } |
| | | 57 | | } |
| | | 58 | | |