Move SafeHandle to managed code and shared by stephentoub · Pull Request #22564 · dotnet/coreclr (original) (raw)
This moves the implementation of SafeHandle from native code in the runtime to managed. I used corert's implementation as a base, and reviewed it again against the existing native implementation, making a few tweaks to better match the existing semantics.
This should be a valid move because of the reduced goals around CERs, thread aborts, etc.
However, there are places in the runtime that access SafeHandle functionality via its native counterpart, so I kept the relevant pieces of the native code intact. Most code will continue to use the managed APIs, but the runtime can continue calling into the native versions when needed.
This also gives a boost to throughput. For this microbenchmark:
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using System; using System.Runtime.InteropServices;
[InProcess] [MemoryDiagnoser] public class Test { public static void Main() => BenchmarkRunner.Run();
private CustomSafeHandle _handle = new CustomSafeHandle();
[Benchmark]
public void AddRelease()
{
bool success = false;
_handle.DangerousAddRef(ref success);
_handle.DangerousRelease();
}
[Benchmark]
public void CreateDispose() => new CustomSafeHandle().Dispose();
}
class CustomSafeHandle : SafeHandle { public CustomSafeHandle() : base((IntPtr)(-1), true) => SetHandle((IntPtr)12345); public override bool IsInvalid => false; protected override bool ReleaseHandle() => true; }
Before:
Method | Mean | Error | StdDev | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
-------------- |----------:|----------:|----------:|------------:|------------:|------------:|--------------------:|
AddRelease | 35.25 ns | 0.4177 ns | 0.3703 ns | - | - | - | - |
CreateDispose | 114.17 ns | 2.1516 ns | 2.0126 ns | 0.0076 | - | - | 32 B |
After:
Method | Mean | Error | StdDev | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
-------------- |---------:|----------:|----------:|------------:|------------:|------------:|--------------------:|
AddRelease | 16.82 ns | 0.2752 ns | 0.2574 ns | - | - | - | - |
CreateDispose | 67.18 ns | 1.3370 ns | 1.3131 ns | 0.0076 | - | - | 32 B |
Contributes to https://github.com/dotnet/coreclr/issues/17903