public static Transfer Receive(SafeHandleMinusOneIsInvalid handle) { if (NativeMethods.ConnectNamedPipe(handle, IntPtr.Zero) == false) { throw new Win32Exception(); } uint available = 0; while (available == 0) { uint bytesRead = 0, thismsg = 0; if (NativeMethods.PeekNamedPipe(handle, null, 0, ref bytesRead, ref available, ref thismsg) == false) { Thread.Sleep(100); available = 0; } } byte[] buffer = new byte[available]; uint read = 0; NativeOverlapped overlapped = new NativeOverlapped(); if (NativeMethods.ReadFile(handle, buffer, (uint)buffer.Length, ref read, ref overlapped) == false) { throw new Win32Exception(); } if (read != available) { throw new InvalidOperationException("Invalid byte count."); } return(Transfer.Deserialize(buffer)); }
private static void Run() { while (!ServiceThread.CancelEvent.WaitOne(0, false)) { try { ServiceThread.Handle = Transfer.Create(); while (!ServiceThread.CancelEvent.WaitOne(0, false)) { var trans = Transfer.Receive(ServiceThread.Handle); try { switch (trans.Command) { case "Start": { using (var service = new ServiceController(trans.ServiceName)) { service.Start(); } } break; case "Stop": { using (var service = new ServiceController(trans.ServiceName)) { service.Stop(); } } break; } } catch (InvalidOperationException ex) { Trace.TraceWarning(ex.Message); } } } catch (Win32Exception) { } catch (ThreadAbortException) { } finally { if (ServiceThread.Handle != null) { ServiceThread.Handle.Close(); } } } }
public static extern bool ReadFile(SafeHandleMinusOneIsInvalid hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, ref uint lpNumberOfBytesRead, ref NativeOverlapped lpOverlapped);
public static extern bool PeekNamedPipe(SafeHandleMinusOneIsInvalid hNamedPipe, byte[] lpBuffer, uint nBufferSize, ref uint lpBytesRead, ref uint lpTotalBytesAvail, ref uint lpBytesLeftThisMessage);
public static extern bool ConnectNamedPipe(SafeHandleMinusOneIsInvalid hNamedPipe, IntPtr lpOverlapped);
public static void Cancel(SafeHandleMinusOneIsInvalid handle) { NativeMethods.CancelIoEx(handle, IntPtr.Zero); }