Created
August 6, 2018 07:45
-
-
Save rozputnii/336c2e852557f70b9c0dd5a579a6254c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.IO; | |
| using System.IO.MemoryMappedFiles; | |
| using System.Runtime.Serialization.Formatters.Binary; | |
| public static class ReadWriteMemoryMappedFile | |
| { | |
| // allocated memory for this memory mapped file (bytes) | |
| private const int MMF_MAX_SIZE = byte.MaxValue; | |
| // how many bytes of the allocated memory can this process access | |
| private const int MMF_VIEW_SIZE = byte.MaxValue; | |
| private static void Write() | |
| { | |
| var mmf = MemoryMappedFile.CreateOrOpen("mmf1", MMF_MAX_SIZE, MemoryMappedFileAccess.ReadWrite); | |
| using (var mmvStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE)) { | |
| var msg = DateTime.Now; | |
| var formatter = new BinaryFormatter(); | |
| formatter.Serialize(mmvStream, msg); | |
| mmvStream.Seek(0, SeekOrigin.Begin); | |
| } | |
| } | |
| private static void Read() | |
| { | |
| var formatter = new BinaryFormatter(); | |
| var buffer = new byte[MMF_VIEW_SIZE]; | |
| try { | |
| using (var mmf = MemoryMappedFile.OpenExisting("mmf1")) | |
| using (var mmvStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE)) { | |
| mmvStream.Read(buffer, 0, MMF_VIEW_SIZE); | |
| var msg = (DateTime) formatter.Deserialize(new MemoryStream(buffer)); | |
| } | |
| } catch (FileNotFoundException e) { | |
| Console.WriteLine(e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment