mirror of https://github.com/dahall/Vanara.git
Merge branch 'master' of https://github.com/dahall/Vanara
commit
7ebd5aaf58
|
@ -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>
|
||||
|
|
|
@ -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()
|
||||
|
|
Loading…
Reference in New Issue