From 20ad66606d28422cd832b2b5afa519fbbc41c691 Mon Sep 17 00:00:00 2001 From: David Hall Date: Wed, 20 Feb 2019 15:29:06 -0700 Subject: [PATCH] Added code to handle singleton binding of device handles. Risk is if system reuses handle during process execution. --- PInvoke/Shared/OverlappedAsyncBase.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/PInvoke/Shared/OverlappedAsyncBase.cs b/PInvoke/Shared/OverlappedAsyncBase.cs index 1acd97a3..ed429d6b 100644 --- a/PInvoke/Shared/OverlappedAsyncBase.cs +++ b/PInvoke/Shared/OverlappedAsyncBase.cs @@ -9,6 +9,8 @@ namespace Vanara.PInvoke /// Helper methods to work with asynchronous methods using . public static class OverlappedAsync { + public static System.Collections.Generic.HashSet boundHandles = new System.Collections.Generic.HashSet(); + /// Cleans up at the end of the callback method. /// The asynchronous result. /// The object passed into the method. @@ -69,7 +71,7 @@ namespace Vanara.PInvoke /// An instance for the asynchronous calls. public static unsafe OverlappedAsyncResult SetupOverlappedFunction(HFILE hDevice, AsyncCallback userCallback, object userState) { - try { ThreadPool.BindHandle(new Microsoft.Win32.SafeHandles.SafeFileHandle((IntPtr)hDevice, false)); } catch { } + BindHandle(hDevice); var ar = new OverlappedAsyncResult(userState, userCallback, hDevice); var o = new Overlapped(0, 0, IntPtr.Zero, ar); ar.Overlapped = o.Pack((code, bytes, pOverlapped) => @@ -83,6 +85,12 @@ namespace Vanara.PInvoke return ar; } + private static void BindHandle(HFILE hDevice) + { + if (boundHandles.Add(hDevice)) + ThreadPool.BindHandle(new Microsoft.Win32.SafeHandles.SafeFileHandle((IntPtr)hDevice, false)); + } + /// Holds all pertinent information for handling results and errors in an overlapped set of method calls. /// public sealed class OverlappedAsyncResult : IAsyncResult