public static bool CreateSingleInstance(EventHandler <DataReceivedEventArgs> handler, string data) { bool isFirstInstance = true; try { var eventHandle = SharedMemoryCommon.CreateOrOpenEventHandle(out isFirstInstance); if (isFirstInstance) { IIpcServer server = new SharedMemoryServer(eventHandle); server.Received += handler; server.Start(); // Register process exit handler to stop the server Process process = Process.GetCurrentProcess(); process.Exited += (s, e) => { log.Info("Closing interprocess communication server"); try { server.Dispose(); } catch (Exception ex) { log.Error("Error closing interprocess communication server", ex); } }; } else { using (IIpcClient client = new SharedMemoryClient(eventHandle)) client.Send(data); } } catch (Exception ex) { log.Error("Error creating single instance of application", ex); } return(isFirstInstance); }
public void Send(string data) { using (var memFile = SharedMemoryCommon.CreateOrOpenMemoryMappedFile()) using (var memView = memFile.CreateViewAccessor()) { var bytes = Encoding.Default.GetBytes(data); memView.Write(SharedMemoryCommon.DataLengthPosition, bytes.Length); memView.WriteArray(SharedMemoryCommon.DataPosition, bytes, 0, bytes.Length); _dataAvailable.Set(); } }
public void Start() { Task.Factory.StartNew(() => { using (var memFile = SharedMemoryCommon.CreateOrOpenMemoryMappedFile()) using (var memView = memFile.CreateViewAccessor()) { // Continue waiting and looping while data available satisfied the wait; stop looping when killer event is set while (WaitHandle.WaitAny(new WaitHandle[] { _killer, _dataAvailable }) == 1) { int length = memView.ReadInt32(SharedMemoryCommon.DataLengthPosition); var data = new byte[length]; memView.ReadArray(SharedMemoryCommon.DataPosition, data, 0, length); OnReceived(new DataReceivedEventArgs(Encoding.Default.GetString(data))); } } }); }