/// <summary> /// Opens a handle to the driver. /// </summary> /// <returns></returns> public static SafeFileHandle OpenDevice( String deviceName, bool useAsync ) { // Open the handle to the driver SafeFileHandle device = Kernel32Import.CreateFile(deviceName, Kernel32Import.GENERIC_READ | Kernel32Import.GENERIC_WRITE, Kernel32Import.FILE_SHARE_READ | Kernel32Import.FILE_SHARE_WRITE, IntPtr.Zero, Kernel32Import.OPEN_EXISTING, useAsync ? Kernel32Import.FILE_FLAG_OVERLAPPED : 0, IntPtr.Zero ); if (device.IsInvalid) { throw new Win32Exception(); } // Bind the handle to the thread pool if performing asynchronous // operation, for later completion if (useAsync) { ThreadPool.BindHandle(device); } return(device); }
internal OverlappedStream( string path, FileMode mode, FileAccess access, FileShare share, uint file_flags ) { if (mode == FileMode.Append) { throw new NotSupportedException("Append mode is not supported in OverlappedStream"); } if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException("path"); } uint file_access = (((access & FileAccess.Read) != 0) ? NativeMethods.GENERIC_READ : 0U) | (((access & FileAccess.Write) != 0) ? NativeMethods.GENERIC_WRITE : 0U); uint file_share = unchecked (((uint)share & ~(uint)FileShare.Inheritable)); uint file_creation = unchecked ((uint)mode); _handle = NativeMethods.CreateFileW(path, file_access, file_share, IntPtr.Zero, file_creation, file_flags, IntPtr.Zero); ASSERT(!_handle.IsInvalid); ASSERT(ThreadPool.BindHandle(_handle)); }
internal Task <Message> ReceiveAsync(Properties properties, ReadAction action, TimeSpan?timeout, CursorHandle cursor) { if (IsClosed) { throw new ObjectDisposedException(nameof(Queue)); } uint timeoutMS = TimeoutInMs(timeout); var msg = new Message(); msg.Props.SetForRead(properties); var ar = new QueueAsyncRequest(msg, _outstanding, timeoutMS, _handle, action, cursor); lock (_outstanding) { _outstanding.Add(ar); // hold a reference to prevent objects being collected if (!_boundToThreadPool) { ThreadPool.BindHandle(_handle); // queue can now use IO completion port _boundToThreadPool = true; } } return(ar.ReceiveAsync()); }
int RunTest() { try { try { using (SafeFileHandle sfh = new SafeFileHandle(CreateFile("test.txt", 0x40000000, 0, 0, 2, 0x80, 0), true)) { ThreadPool.BindHandle(sfh); } } catch (Exception ex) { if ((uint)ex.HResult == (uint)0x80070057) // E_INVALIDARG, the handle isn't overlapped { Console.WriteLine("Test passed"); return(100); } else { Console.WriteLine($"Got wrong error - HResult: 0x{ex.HResult:x}, Exception: {ex}"); } } } finally { if (File.Exists("test.txt")) { File.Delete("test.txt"); } } Console.WriteLine("Didn't get argument null exception"); return(99); }
protected void InitializeHandle(Microsoft.Win32.SafeHandles.SafePipeHandle handle, bool isExposed, bool isAsync) { isAsync &= _canUseAsync; if (isAsync) { bool flag = false; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); try { flag = ThreadPool.BindHandle(handle); } finally { CodeAccessPermission.RevertAssert(); } if (!flag) { throw new IOException(System.SR.GetString("IO_IO_BindHandleFailed")); } } this.m_handle = handle; this.m_isAsync = isAsync; this.m_isHandleExposed = isExposed; this.m_isFromExistingHandle = isExposed; }
private SafeFileHandle CreateHandle(int segmentId) { uint fileAccess = Native32.GENERIC_READ | Native32.GENERIC_WRITE; uint fileShare = unchecked (((uint)FileShare.ReadWrite & ~(uint)FileShare.Inheritable)); uint fileCreation = unchecked ((uint)FileMode.OpenOrCreate); uint fileFlags = Native32.FILE_FLAG_OVERLAPPED; fileFlags = fileFlags | Native32.FILE_FLAG_NO_BUFFERING; if (deleteOnClose) { fileFlags = fileFlags | Native32.FILE_FLAG_DELETE_ON_CLOSE; } var logHandle = Native32.CreateFileW( GetSegmentName(segmentId), fileAccess, fileShare, IntPtr.Zero, fileCreation, fileFlags, IntPtr.Zero); if (preallocateSegment) { SetFileSize(FileName, logHandle, SegmentSize); } try { ThreadPool.BindHandle(logHandle); } catch (Exception e) { throw new Exception("Error binding log handle for " + GetSegmentName(segmentId) + ": " + e.ToString()); } return(logHandle); }
private static void BindHandle(HFILE hDevice) { if (boundHandles.Add(hDevice)) { ThreadPool.BindHandle(new Microsoft.Win32.SafeHandles.SafeFileHandle((IntPtr)hDevice, false)); } }
public async Task WinUsb_WritePipeAsync_Overlapped_Test() { var devicePath = @"<path to your USB device>"; using (var handle = CreateFile( devicePath, ACCESS_MASK.GenericRight.GENERIC_READ | ACCESS_MASK.GenericRight.GENERIC_WRITE, FileShare.FILE_SHARE_READ | FileShare.FILE_SHARE_WRITE, IntPtr.Zero, CreationDisposition.OPEN_EXISTING, CreateFileFlags.FILE_FLAG_OVERLAPPED, SafeObjectHandle.Null)) { ThreadPool.BindHandle(handle); if (!WinUsb_Initialize(handle, out SafeUsbHandle usbHandle)) { throw new PInvoke.Win32Exception(Marshal.GetLastWin32Error()); } Assert.True(WinUsb_QueryPipe(usbHandle, alternateInterfaceNumber: 0, pipeIndex: 0, out WINUSB_PIPE_INFORMATION input)); var readTask = WinUsb_WritePipeAsync(usbHandle, input.PipeId, Array.Empty <byte>(), default); Assert.Equal(0, await readTask.ConfigureAwait(false)); } }
private IpcPort(string portName, PipeHandle handle) { this._portName = portName; this._handle = handle; this._cacheable = true; ThreadPool.BindHandle(this._handle.Handle); }
public async Task WinUsb_ReadPipeAsync_Cancelled_Test() { var devicePath = @"<path to your USB device>"; using (var handle = CreateFile( devicePath, ACCESS_MASK.GenericRight.GENERIC_READ | ACCESS_MASK.GenericRight.GENERIC_WRITE, FileShare.FILE_SHARE_READ | FileShare.FILE_SHARE_WRITE, IntPtr.Zero, CreationDisposition.OPEN_EXISTING, CreateFileFlags.FILE_FLAG_OVERLAPPED, SafeObjectHandle.Null)) { ThreadPool.BindHandle(handle); if (!WinUsb_Initialize(handle, out SafeUsbHandle usbHandle)) { throw new PInvoke.Win32Exception(Marshal.GetLastWin32Error()); } Assert.True(WinUsb_QueryPipe(usbHandle, alternateInterfaceNumber: 0, pipeIndex: 0, out WINUSB_PIPE_INFORMATION input)); byte[] buffer = new byte[100]; var cts = new CancellationTokenSource(); var readTask = WinUsb_ReadPipeAsync(usbHandle, input.PipeId, buffer, cts.Token); cts.Cancel(); var ex = await Assert.ThrowsAsync <PInvoke.Win32Exception>(() => readTask.AsTask()); Assert.Equal(Win32ErrorCode.ERROR_OPERATION_ABORTED, ex.NativeErrorCode); } }
int RunTest() { try { try { using (FileStream fs1 = new FileStream("test.txt", FileMode.Create)) { ThreadPool.BindHandle(fs1.SafeFileHandle); } } catch (Exception ex) { if (ex.ToString().IndexOf("0x80070057") != -1) // E_INVALIDARG, the handle isn't overlapped { Console.WriteLine("Test passed"); return(100); } else { Console.WriteLine("Got wrong error: {0}", ex); } } } finally { if (File.Exists("test.txt")) { File.Delete("test.txt"); } } Console.WriteLine("Didn't get argument null exception"); return(99); }
protected DeviceIOInfo(SafeFileHandle device, Boolean useAsync) { m_device = device; if (useAsync) { ThreadPool.BindHandle(m_device); } }
public LocalStorageDevice(string filename, bool enablePrivileges = false, bool useIoCompletionPort = false, bool unbuffered = false, bool deleteOnClose = false) { this.filename = filename; this.enablePrivileges = enablePrivileges; this.useIoCompletionPort = useIoCompletionPort; if (enablePrivileges) { Native32.EnableProcessPrivileges(); } Native32.GetDiskFreeSpace(filename.Substring(0, 3), out lpSectorsPerCluster, out lpBytesPerSector, out lpNumberOfFreeClusters, out lpTotalNumberOfClusters); uint fileAccess = Native32.GENERIC_READ | Native32.GENERIC_WRITE; // uint fileShare = unchecked(((uint)FileShare.ReadWrite & ~(uint)FileShare.Inheritable)); uint fileShare = unchecked (((uint)FileShare.Read & ~(uint)FileShare.Inheritable)); uint fileCreation = unchecked ((uint)FileMode.OpenOrCreate); uint fileFlags = Native32.FILE_FLAG_OVERLAPPED; if (unbuffered) { fileFlags = fileFlags | Native32.FILE_FLAG_NO_BUFFERING; } if (deleteOnClose) { fileFlags = fileFlags | Native32.FILE_FLAG_DELETE_ON_CLOSE; } logHandle = Native32.CreateFileW(filename, fileAccess, fileShare, IntPtr.Zero, fileCreation, fileFlags, IntPtr.Zero); if (enablePrivileges) { Native32.EnableVolumePrivileges(filename, logHandle); } if (useIoCompletionPort) { ioCompletionPort = Native32.CreateIoCompletionPort( logHandle, IntPtr.Zero, (uint)logHandle.DangerousGetHandle().ToInt64(), 0); } ThreadPool.BindHandle(logHandle); }
/// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> private void InitializeAsyncHandle(SafePipeHandle handle) { // If the handle is of async type, bind the handle to the ThreadPool so that we can use // the async operations (it's needed so that our native callbacks get called). if (!ThreadPool.BindHandle(handle)) { throw new IOException(SR.IO_BindHandleFailed); } }
public void Create(string fileName) { _fileHandle = NativeMethods.CreateFile(fileName, FileAccess.Write | FileAccess.Read, FileShare.ReadWrite, IntPtr.Zero, FileMode.OpenOrCreate, NativeMethods.EFileAttributes.Overlapped, IntPtr.Zero); _offset = (int)NativeMethods.SetFilePointer(_fileHandle, 0, SeekOrigin.End, out var hr); ThreadPool.BindHandle(_fileHandle); }
/// <summary> /// Creates a SafeFileHandle for the specified segment. This can be used by derived classes to prepopulate logHandles in the constructor. /// </summary> protected internal static SafeFileHandle CreateHandle(int segmentId, bool disableFileBuffering, bool deleteOnClose, bool preallocateFile, long segmentSize, string fileName, IntPtr ioCompletionPort) { uint fileAccess = Native32.GENERIC_READ | Native32.GENERIC_WRITE; uint fileShare = unchecked (((uint)FileShare.ReadWrite & ~(uint)FileShare.Inheritable)); uint fileCreation = unchecked ((uint)FileMode.OpenOrCreate); uint fileFlags = Native32.FILE_FLAG_OVERLAPPED; if (disableFileBuffering) { fileFlags = fileFlags | Native32.FILE_FLAG_NO_BUFFERING; } if (deleteOnClose) { fileFlags = fileFlags | Native32.FILE_FLAG_DELETE_ON_CLOSE; // FILE_SHARE_DELETE allows multiple FASTER instances to share a single log directory and each can specify deleteOnClose. // This will allow the files to persist until all handles across all instances have been closed. fileShare = fileShare | Native32.FILE_SHARE_DELETE; } var logHandle = Native32.CreateFileW( GetSegmentName(fileName, segmentId), fileAccess, fileShare, IntPtr.Zero, fileCreation, fileFlags, IntPtr.Zero); if (logHandle.IsInvalid) { var error = Marshal.GetLastWin32Error(); throw new IOException($"Error creating log file for {GetSegmentName(fileName, segmentId)}, error: {error}", Native32.MakeHRFromErrorCode(error)); } if (preallocateFile && segmentSize != -1) { SetFileSize(fileName, logHandle, segmentSize); } if (ioCompletionPort != IntPtr.Zero) { ThreadPool.GetMaxThreads(out int workerThreads, out _); Native32.CreateIoCompletionPort(logHandle, ioCompletionPort, (UIntPtr)(long)logHandle.DangerousGetHandle(), (uint)(workerThreads + NumCompletionThreads)); } else { try { ThreadPool.BindHandle(logHandle); } catch (Exception e) { throw new FasterException("Error binding log handle for " + GetSegmentName(fileName, segmentId) + ": " + e.ToString()); } } return(logHandle); }
private IpcPort(string portName, PipeHandle handle) { _portName = portName; _handle = handle; _cacheable = true; #pragma warning disable 618 // Bind the current handle to the threadpool for IOCompletion ThreadPool.BindHandle(_handle.Handle); #pragma warning restore 618 }
private SafeFileHandle GetOrAddHandle(int _segmentId) { return(logHandles.GetOrAdd(_segmentId, segmentId => { uint fileAccess = Native32.GENERIC_READ | Native32.GENERIC_WRITE; uint fileShare = unchecked (((uint)FileShare.ReadWrite & ~(uint)FileShare.Inheritable)); uint fileCreation = unchecked ((uint)FileMode.OpenOrCreate); uint fileFlags = Native32.FILE_FLAG_OVERLAPPED; if (unbuffered) { fileFlags = fileFlags | Native32.FILE_FLAG_NO_BUFFERING; } if (deleteOnClose) { fileFlags = fileFlags | Native32.FILE_FLAG_DELETE_ON_CLOSE; } var logHandle = Native32.CreateFileW( GetSegmentName(segmentId), fileAccess, fileShare, IntPtr.Zero, fileCreation, fileFlags, IntPtr.Zero); if (enablePrivileges) { Native32.EnableVolumePrivileges(ref dirname, logHandle); } SetFileSize(logHandle, segmentSize); if (useIoCompletionPort) { ioCompletionPort = Native32.CreateIoCompletionPort( logHandle, IntPtr.Zero, (uint)logHandle.DangerousGetHandle().ToInt64(), 0); } try { ThreadPool.BindHandle(logHandle); } catch (Exception e) { Console.WriteLine("Log handle! : {0}", logHandle.ToString()); Console.WriteLine(e.ToString()); Environment.Exit(0); } return logHandle; })); }
public async Task <bool> OpenAsync() { deviceHandle = Kernel32.CreateFile(DevicePath, NativeFileAccess.FILE_GENERIC_WRITE | NativeFileAccess.FILE_GENERIC_READ, NativeFileShare.FILE_SHARE_WRITE | NativeFileShare.FILE_SHARE_READ, IntPtr.Zero, NativeFileMode.OPEN_EXISTING, NativeFileFlag.FILE_ATTRIBUTE_NORMAL | NativeFileFlag.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (deviceHandle.IsInvalid || deviceHandle.IsClosed) { return(false); } if (UseOverlappedTransfers) { ThreadPool.BindHandle(deviceHandle); // needed for overlapped I/O } winUsbHandle = new SafeWinUsbHandle(); if (WinUsb.NativeMethods.WinUsb_Initialize(deviceHandle, ref winUsbHandle) == false) { return(false); } int trueVal = 1; int timeout = 500; int timeoutShort = 50; WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, peripheralResponseEndpoint, PipePolicy.AutoClearStall, 4, ref trueVal); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, peripheralResponseEndpoint, PipePolicy.PipeTransferTimeout, 4, ref timeoutShort); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, pinReportEndpoint, PipePolicy.AutoClearStall, 4, ref trueVal); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, pinReportEndpoint, PipePolicy.PipeTransferTimeout, 4, ref timeout); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, peripheralConfigEndpoint, PipePolicy.AutoClearStall, 4, ref trueVal); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, peripheralConfigEndpoint, PipePolicy.PipeTransferTimeout, 4, ref timeout); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, pinConfigEndpoint, PipePolicy.AutoClearStall, 4, ref trueVal); WinUsb.NativeMethods.WinUsb_SetPipePolicy(winUsbHandle, pinConfigEndpoint, PipePolicy.PipeTransferTimeout, 4, ref timeout); IsOpen = true; BeginRead(pinReportEndpoint, pinReportBuffer, pinReportBuffer.Length, pinStateCallback, null); // kick off our first pin read return(true); }
public void Open(string port) { m_hFile = CreateFile(port, (uint)((m_bRead?GENERIC_READ:0) | (m_bWrite?GENERIC_WRITE:0)), 0, 0, 3, 0x40000000, 0); if (m_hFile <= 0) { m_hFile = 0; throw new FileNotFoundException("Unable to open " + port); } m_sPort = port; ThreadPool.BindHandle(new IntPtr(m_hFile)); }
internal WirekiteDevice(WirekiteService service, String devicePath, SafeFileHandle deviceHandle, IntPtr interfaceHandle) { _service = service; DevicePath = devicePath; _deviceHandle = deviceHandle; _interfaceHandle = interfaceHandle; ThreadPool.BindHandle(_deviceHandle); SubmitReadRequest(); ResetConfiguration(); _deviceState = DeviceState.Ready; }
/// <summary> /// 将操作系统句柄绑定到线程池 /// </summary> /// <param name="osHandle">系统句柄</param> /// <returns>设置结果</returns> public bool SetBindHandle(IntPtr osHandle) { try { return(ThreadPool.BindHandle(osHandle)); } catch (Exception e) { //句柄无效 return(false); } }
private void StartRaisingEvents() { if (this.disposed) { throw new ObjectDisposedException(base.GetType().Name); } try { new EnvironmentPermission(PermissionState.Unrestricted).Assert(); if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException(SR.GetString("WinNTRequired")); } } finally { CodeAccessPermission.RevertAssert(); } if (this.IsSuspended()) { this.enabled = true; } else { if (!this.readGranted) { string fullPath = System.IO.Path.GetFullPath(this.directory); new FileIOPermission(FileIOPermissionAccess.Read, fullPath).Demand(); this.readGranted = true; } if (this.IsHandleInvalid) { this.directoryHandle = Microsoft.Win32.NativeMethods.CreateFile(this.directory, 1, 7, null, 3, 0x42000000, new SafeFileHandle(IntPtr.Zero, false)); if (this.IsHandleInvalid) { throw new FileNotFoundException(SR.GetString("FSW_IOError", new object[] { this.directory })); } this.stopListening = false; Interlocked.Increment(ref this.currentSession); new SecurityPermission(PermissionState.Unrestricted).Assert(); try { ThreadPool.BindHandle(this.directoryHandle); } finally { CodeAccessPermission.RevertAssert(); } this.enabled = true; this.Monitor(null); } } }
public static SafeFileHandle OpenHandle(string fullPath, bool asDirectory, bool writeMode = false, bool backupMode = false, bool asyncMode = true, int additionalFlags = 0) { string root = fullPath.Substring(0, Win32PathInternal.GetRootLength(fullPath.AsSpan())); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException("path"); } if (asyncMode) { additionalFlags |= (int)FileOptions.Asynchronous; } using (Lfs.EnterDisableMediaInsertionPrompt()) { SafeFileHandle handle = Win32Api.Kernel32.CreateFile( fullPath, writeMode ? Win32Api.Kernel32.GenericOperations.GENERIC_WRITE | Win32Api.Kernel32.GenericOperations.GENERIC_READ : Win32Api.Kernel32.GenericOperations.GENERIC_READ, FileShare.ReadWrite | FileShare.Delete, FileMode.Open, ((asDirectory || backupMode) ? Win32Api.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : 0) | additionalFlags); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Win32Api.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) { errorCode = Win32Api.Errors.ERROR_ACCESS_DENIED; } throw PalWin32FileStream.GetExceptionForWin32Error(errorCode, fullPath); } if (((FileOptions)additionalFlags).Bit(FileOptions.Asynchronous)) { handle._SetAsync(true); ThreadPool.BindHandle(handle); } else { handle._SetAsync(false); } return(handle); } }
public WinUsbDevice(String path, WinUsbRegistry registry) { this.Registry = registry; DeviceHandle = Kernel32.CreateFile(path, NativeFileAccess.FILE_GENERIC_WRITE | NativeFileAccess.FILE_GENERIC_READ, NativeFileShare.FILE_SHARE_WRITE | NativeFileShare.FILE_SHARE_READ, IntPtr.Zero, NativeFileMode.OPEN_EXISTING, NativeFileFlag.FILE_ATTRIBUTE_NORMAL | NativeFileFlag.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (DeviceHandle.IsInvalid || DeviceHandle.IsClosed) { throw new Win32Exception(); } ThreadPool.BindHandle(DeviceHandle); SafeWinUsbInterfaceHandle InterfaceHandle; if (!WinUsb_Initialize(DeviceHandle, out InterfaceHandle)) { throw new Win32Exception(); } if (InterfaceHandle.IsInvalid || InterfaceHandle.IsClosed) { throw new Win32Exception(); } InterfaceHandles = new SafeWinUsbInterfaceHandle[1] { InterfaceHandle }; foreach (UsbInterfaceInfo ifinfo in UsbDeviceInfo.FromDevice(this).FindConfiguration(Configuration).Interfaces) { foreach (UsbEndpointDescriptor epinfo in ifinfo.Endpoints) { int epidx = epinfo.EndpointAddress & 0x7F; if ((epinfo.EndpointAddress & 0x80) != 0) { if (EndpointToInterfaceIn.Length <= epidx) { Array.Resize(ref EndpointToInterfaceIn, epidx + 1); } EndpointToInterfaceIn[epidx] = ifinfo.Descriptor.InterfaceNumber; } else { if (EndpointToInterfaceOut.Length <= epidx) { Array.Resize(ref EndpointToInterfaceOut, epidx + 1); } EndpointToInterfaceOut[epidx] = ifinfo.Descriptor.InterfaceNumber; } } } }
static unsafe void Main(string[] args) { var safeFileHandle = CreateFile(@"C:\Windows\win.ini", Win32Api.GENERIC_READ, Win32Api.FILE_SHARE_READ, (IntPtr)null, Win32Api.OPEN_EXISTING, Win32Api.FILE_FLAG_OVERLAPPED, new SafeFileHandle(IntPtr.Zero, false)); #if MANUAL_BIND_IOCP SafeFileHandle iocpHandle = CreateIoCompletionPort(INVALID_FILE_HANDLE, INVALID_IOCP_HANDLE, UIntPtr.Zero, 0); CreateIoCompletionPort(safeFileHandle.DangerousGetHandle(), iocpHandle.DangerousGetHandle(), UIntPtr.Zero, 0); int threadCount = Environment.ProcessorCount * 2; for (int i = 0; i < threadCount; i++) { new Thread(() => { try { UInt32 lpNumberOfBytes; IntPtr lpCompletionKey, lpOverlapped; while (GetQueuedCompletionStatus(iocpHandle.DangerousGetHandle(), out lpNumberOfBytes, out lpCompletionKey, out lpOverlapped, INFINITE_TIMEOUT)) { NativeOverlapped *native = (NativeOverlapped *)lpOverlapped; //推入到IO线程的任务队列 ThreadPool.UnsafeQueueNativeOverlapped(native); } } finally { } }) { IsBackground = true }.Start(); } #else ThreadPool.BindHandle(safeFileHandle); #endif byte[] buffer = new byte[16384]; AsyncResult ar = new AsyncResult(buffer); NativeOverlapped *nativeOverlapped = new Overlapped(0, 0, IntPtr.Zero, ar).Pack(ReadCompletionCallback, buffer); fixed(byte *pBuf = buffer) { ReadFile(safeFileHandle, pBuf, 16384, IntPtr.Zero, nativeOverlapped); } int workerNums, ioNums; ThreadPool.GetAvailableThreads(out workerNums, out ioNums); Console.WriteLine("from main thread: available work threads:{0}, io threads:{1}", workerNums, ioNums); Console.WriteLine($"Total threads:{Process.GetCurrentProcess().Threads.Count}"); Console.ReadKey(); ThreadPool.GetAvailableThreads(out workerNums, out ioNums); Console.WriteLine("from main thread: available work threads:{0}, io threads:{1}", workerNums, ioNums); Console.WriteLine($"Total threads:{Process.GetCurrentProcess().Threads.Count}"); }
protected GenericAsyncStream(SafeHandle handle) { System.Diagnostics.Debug.Assert(handle != null); m_handle = handle; if (ThreadPool.BindHandle(m_handle) == false) { throw new IOException("BindHandle Failed"); } m_outstandingRequests = ArrayList.Synchronized(new ArrayList()); }
int RunTest() { try { try { using (SafeFileHandle sfh = new SafeFileHandle(CreateFile("test.txt", 0x40000000, 0, 0, 2, 0x40000000, 0), true)) { try { if (ThreadPool.BindHandle(sfh)) { Console.WriteLine("BindHandle call succeeded"); } else { Console.WriteLine("Unexpected: BindHandle call failed"); return(98); } } catch (Exception e) { Console.WriteLine($"Unexpected exception on 1st call - HResult: 0x{e.HResult:x}, Exception: {e}"); return(92); } ThreadPool.BindHandle(sfh); } } catch (Exception ex) { if ((uint)ex.HResult == (uint)0x80070057) // E_INVALIDARG, we've already bound the handle. { Console.WriteLine("Test passed"); return(100); } else { Console.WriteLine($"Got wrong error - HResult: 0x{ex.HResult:x}, Exception: {ex}"); } } } finally { if (File.Exists("test.txt")) { File.Delete("test.txt"); } } return(99); }
int RunTest() { try { try { using (SafeFileHandle sfh = new SafeFileHandle(CreateFile("test.txt", 0x40000000, 0, 0, 2, 0x40000000, 0), true)) { try { if (ThreadPool.BindHandle(sfh)) { Console.WriteLine("BindHandle call succeeded"); } else { Console.WriteLine("Unexpected: BindHandle call failed"); return(98); } } catch (Exception e) { Console.WriteLine("Unexpected exception on 1st call: {0}", e); return(92); } ThreadPool.BindHandle(sfh); } } catch (Exception ex) { if (ex.ToString().IndexOf("0x80070057") != -1) // E_INVALIDARG, we've already bound the handle. { Console.WriteLine("Test passed"); return(100); } else { Console.WriteLine("Got wrong error: {0}", ex); } } } finally { if (File.Exists("test.txt")) { File.Delete("test.txt"); } } return(99); }
public DeviceFile(string fileName) { handle = NativeMethods.CreateFile(fileName, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, (FileAttributes)FileFlags.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (handle.IsInvalid) { throw new Win32Exception("CreateFile"); } if (!ThreadPool.BindHandle(handle)) { handle.Dispose(); throw new UnexpectedResultException("ThreadPool.BindHandle() failed"); } }