Call to closeMethod in GenericSafeHandle. (#161)

pull/164/head
NN 2020-08-27 19:25:14 +03:00 committed by GitHub
parent d214434cda
commit 80bfe2ce20
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 1 deletions

View File

@ -25,7 +25,13 @@ namespace Vanara.InteropServices
/// <param name="closeMethod">The delegate method for closing the handle.</param>
/// <param name="ownsHandle"><see langword="true"/> to reliably release the handle during the finalization phase; <see langword="false"/> to prevent reliable release (not recommended).</param>
/// <exception cref="System.ArgumentNullException">closeMethod</exception>
public GenericSafeHandle(IntPtr ptr, Func<IntPtr, bool> closeMethod, bool ownsHandle = true) : base(ownsHandle) => SetHandle(ptr);
public GenericSafeHandle(IntPtr ptr, Func<IntPtr, bool> closeMethod, bool ownsHandle = true) : base(ownsHandle)
{
if (closeMethod == null) throw new ArgumentNullException(nameof(closeMethod));
SetHandle(ptr);
CloseMethod = closeMethod;
}
/// <summary>Gets or sets the close method.</summary>
/// <value>The close method.</value>

View File

@ -23,6 +23,55 @@ namespace Vanara.InteropServices.Tests
h = new GenericSafeHandle(IntPtr.Zero, p => true);
Assert.That(h.IsInvalid);
}
[Test]
public void GenericSafeHandleCloseMethodNull()
{
Assert.Throws<ArgumentNullException>(() => new GenericSafeHandle((IntPtr)1, null));
}
[Test]
public void GenericSafeHandleCloseMethodTest()
{
var i = 0;
using (var h = new GenericSafeHandleWithSetHandle(ptr =>
{
i = 1;
return true;
}))
{
h.SetHandle((IntPtr)1);
}
Assert.AreEqual(1, i);
}
private class GenericSafeHandleWithSetHandle : GenericSafeHandle
{
public GenericSafeHandleWithSetHandle(Func<IntPtr, bool> closeMethod) : base(closeMethod)
{}
public new void SetHandle(IntPtr handle)
{
base.SetHandle(handle);
}
}
[Test]
public void GenericSafeHandleCloseMethodWithHandleTest()
{
var i = 0;
using (new GenericSafeHandle((IntPtr)1, ptr =>
{
i = 1;
return true;
}))
{
}
Assert.AreEqual(1, i);
}
[Test]
public void GenericSafeHandleTest1()