/// <summary> /// Send a serializeable object through the shared memory /// and wait for it to be picked up /// </summary> /// <param name="transferObject"> the object to send</param> public void SendObject(TransferItemType transferObject) { // create a memory stream, initialize size using (MemoryStream ms = new MemoryStream()) { // get a formatter to serialize with BinaryFormatter formatter = new BinaryFormatter(); try { // serialize the object to the stream formatter.Serialize(ms, transferObject); // get the bytes for the serialized object byte[] bytes = ms.ToArray(); // check that this object will fit if (bytes.Length + sizeof(Int32) > MemoryRegionSize) { string msg = $"{typeof(TransferItemType)} object instance serialized" + $"to {bytes.Length} bytes which is too large for the shared memory region"; throw new ArgumentException(msg, nameof(transferObject)); } // write to the shared memory region using (MemoryMappedViewStream stream = MemMappedFile.CreateViewStream()) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(bytes.Length); // write the size writer.Write(bytes); // write the object } } finally { // signal the other process using the mutex to tell it // to do receive processing MutexForSharedMem.ReleaseMutex(); // wait for the other process to signal it has received // and we can move on MutexForSharedMem.WaitOne(); } } }
/// <summary> /// Wait for an object to hit the shared memory and then deserialize it /// </summary> /// <returns>object passed</returns> public TransferItemType ReceiveObject() { // wait on the mutex for an object to be queued by the sender MutexForSharedMem.WaitOne(); // get the object from the shared memory byte[] serializedObj = null; using (MemoryMappedViewStream stream = MemMappedFile.CreateViewStream()) { BinaryReader reader = new BinaryReader(stream); int objectLength = reader.ReadInt32(); serializedObj = reader.ReadBytes(objectLength); } // set up the memory stream with the object bytes using (MemoryStream ms = new MemoryStream(serializedObj)) { // set up a binary formatter BinaryFormatter formatter = new BinaryFormatter(); // get the object to return TransferItemType item; try { item = (TransferItemType)formatter.Deserialize(ms); } finally { // signal that we received the object using the mutex MutexForSharedMem.ReleaseMutex(); } // give them the object return(item); } }