public void StoreUpdatesMetadata() { using (var indexFile = MemoryMappedFile.CreateNew("index", SIZE_1MB)) using (var dataFile = MemoryMappedFile.CreateNew("data", SIZE_1MB)) using (var engine = FileStorageEngineFactory.NewInstance(indexFile, dataFile)) { engine.Insert(Guid.NewGuid(), BitConverter.GetBytes(UInt64.MaxValue)); using (var indexMetadataAccessor = indexFile.CreateViewAccessor(0, INDEX_METADATA_SIZE)) { var nextBstNode = indexMetadataAccessor.ReadInt64(0); Assert.Equal(1, nextBstNode); } using (var dataMetadataAccessor = dataFile.CreateViewAccessor(0, INDEX_METADATA_SIZE)) { var nextBstNode = dataMetadataAccessor.ReadInt64(0); Assert.Equal(DATA_METADATA_SIZE + 8, nextBstNode); } } }
public void run() { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("procfile", 10000)) { newPrc.Start(); Thread.Sleep(500); int i; while (true) { using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { sem.WaitOne(); BinaryReader reader = new BinaryReader(stream); i = reader.ReadInt32(); i = (int)i / 254; richTextBox1.Invoke(new Action(() => richTextBox1.Text += ("Pressed " + i.ToString()) + " button\n")); } } } }
public MemoryMappedArray(int size0, int size1) { if (size0 <= 0) { throw new ArgumentOutOfRangeException("size0"); } if (size1 <= 0) { throw new ArgumentOutOfRangeException("size1"); } this.size0 = size0; this.size1 = size1; this.numElements = checked ((long)size0 * size1); this.sizeOfT = Marshal.SizeOf(typeof(T)); var bytes = checked (this.numElements * this.sizeOfT); this.memoryMappedFile = MemoryMappedFile.CreateNew(null, bytes); // create accessor for data this.accessor = this.memoryMappedFile.CreateViewAccessor(0L, bytes); }
public static void Initialize(string memoryName, long argsSize) { ArgsImporter.argsSize = argsSize; mutexName = memoryName + "_argsMutex"; memoryFileName = memoryFileName + "_argsFile"; mutex = new Mutex(true, mutexName, out bool t); IsMainApp = t; if (IsMainApp == true) { memoryFile = MemoryMappedFile.CreateNew(memoryFileName, argsSize); mutex.ReleaseMutex(); catchArgsThread = new Thread(() => CatchArgsLoop(memoryFile)); catchArgsThread.Start(); } }
static void Main() { Test t = new Test() { dt1 = DateTime.MaxValue, b = 42 }; Console.WriteLine("Managed size: " + SizeOfType(typeof(Test))); Console.WriteLine("Unmanaged size: " + Marshal.SizeOf(t)); using (MemoryMappedFile file = MemoryMappedFile.CreateNew(null, 1)) using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor()) { accessor.Write(0L, ref t); long pos = 0; for (int i = 0; i < 9; i++) { Console.Write("|" + accessor.ReadByte(pos++)); } Console.Write("|\n"); } }
public void AllowFinaliation() { // Explicitly do not dispose, to allow finalization to happen, just to try to verify // that nothing fails when it does. MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096); MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(); var mmfWeak = new WeakReference <MemoryMappedFile>(mmf); var accWeak = new WeakReference <MemoryMappedViewAccessor>(acc); mmf = null; acc = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.False(mmfWeak.TryGetTarget(out mmf)); Assert.False(accWeak.TryGetTarget(out acc)); }
internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId) { Namespace = @namespace; Key = key; _memoryMappedFile = MemoryMappedFile.CreateNew( MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId), bufferSize); StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite); ProfilerRequestsInformation = new EventWaitHandle(false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId)); InformationReadyForProfiler = new EventWaitHandle(false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId)); InformationReadByProfiler = new EventWaitHandle(false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId)); DataCommunication = new byte[bufferSize]; PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned); }
public void VerifyCreateNewException <EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) where EXCTYPE : Exception { iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } }
/// <summary> /// Creates a circular array that occupies specified amount of space /// </summary> /// <param name="size">Total size of this data structure</param> public MemoryMappedQueue(int size, bool writer, string name) { _readPointer = 0; _writePointer = 0; _overflowWritePointer = -1; _usingOverflowWritePointer = false; _writer = writer; _pointerSize = sizeof(long); _key = new Mutex(initiallyOwned: _writer, name: name); // Ensure specified size is within bounds (2GB) if (size >= int.MaxValue) { throw new ArgumentException("Addressable size is too large.", nameof(size)); } // Ensure that there is enough room for a little data else if (size < 2 * _pointerSize) { throw new ArgumentException("Specified size is too small", nameof(size)); } _dataSize = size; _data = new byte[_dataSize]; string dataFileName = name + "_data"; string pointersFileName = name + "_pointers"; // Access the memory mapped file if (writer) { _dataFile = MemoryMappedFile.CreateNew(dataFileName, _dataSize, MemoryMappedFileAccess.ReadWrite); _pointersFile = MemoryMappedFile.CreateNew(pointersFileName, 3 * _pointerSize, MemoryMappedFileAccess.ReadWrite); storeWritePointer(); } else { _dataFile = MemoryMappedFile.OpenExisting(dataFileName, MemoryMappedFileRights.Read); _pointersFile = MemoryMappedFile.OpenExisting(pointersFileName, MemoryMappedFileRights.ReadWrite); storeReadPointer(); } }
//=================================================================== // Directory //=================================================================== /// Directory初期化 /// @todo(me) 全体的に例外処理を考慮していないコード。要注意。 /// @return 初期化が成功したか public bool InitDirectory() { // プログラム全体で一回だけCreate/CloseすればよいのでCloseはしない if (IsDirectoryInitialized()) return true; // 仮想メモリ(Directory)の作成 /// @todo(me) あまりにも邪悪な例外処理の使い方。なんとかしたい。 MemoryMappedFile tmpDirectory; bool alreadyExists = true; try { tmpDirectory = MemoryMappedFile.OpenExisting(DirectoryName); } catch (FileNotFoundException) { tmpDirectory = MemoryMappedFile.CreateNew(DirectoryName, this.sizeOfDirectory); alreadyExists = false; } // ビューの作成 MemoryMappedViewStream tmpViewOfDirectory = tmpDirectory.CreateViewStream(); // 最初に共有メモリを作成した場合は0クリアしておく if (!alreadyExists) { for (int i = 0; i < this.sizeOfDirectory; i++) { tmpViewOfDirectory.Seek(i, SeekOrigin.Begin); tmpViewOfDirectory.WriteByte(0); } } // Mutexの作成 Mutex tmpMutexDirectory = new Mutex(false, DirectoryMutexName); // フィールドに設定 this.directory = tmpDirectory; this.viewOfDirectory = tmpViewOfDirectory; this.mutexDirectory = tmpMutexDirectory; Trace.WriteLine("****Interprocess: InitDirectory Done"); return true; }
void IRenderHandler.OnPaint(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height, Image image) { //File.AppendAllText("DEBUG.txt", DateTime.Now.ToLongTimeString() + this.GetHashCode() + " ONPAINT " + isPopup + " " + buffer + " - " + width + "x" + height + " " + image.GetHashCode() + Environment.NewLine); if (image.Dispatcher.HasShutdownStarted || (dirtyRect.X == 0 && dirtyRect.Y == 0 && dirtyRect.Width == 0 && dirtyRect.Height == 0)) { return; } if (isPopup) { CurrentPopupRenderInfo = new RenderInfo(isPopup, dirtyRect, buffer, width, height, image); ReleaseMemoryMappedView(ref memoryMappedFile, ref memoryMappedViewAccessor); memoryMappedFile = MemoryMappedFile.CreateNew(null, CurrentRenderInfo.NumberOfBytes, MemoryMappedFileAccess.ReadWrite); memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(); var data = texA.LockRectangle(0, LockFlags.ReadOnly); CopyMemoryGentle(data.DataPointer, memoryMappedViewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), CurrentRenderInfo.NumberOfBytes); texA.UnlockRectangle(0); ReleaseMemoryMappedView(ref popupMemoryMappedFile, ref popupMemoryMappedViewAccessor); popupMemoryMappedFile = MemoryMappedFile.CreateNew(null, CurrentPopupRenderInfo.NumberOfBytes, MemoryMappedFileAccess.ReadWrite); popupMemoryMappedViewAccessor = popupMemoryMappedFile.CreateViewAccessor(); CopyMemoryGentle(CurrentPopupRenderInfo.Buffer, popupMemoryMappedViewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), CurrentPopupRenderInfo.NumberOfBytes); DirectXRender(CurrentPopupRenderInfo); } else { CurrentRenderInfo.IsPopup = isPopup; CurrentRenderInfo.DirtyRect = dirtyRect; CurrentRenderInfo.Buffer = buffer; CurrentRenderInfo.Width = width; CurrentRenderInfo.Height = height; CurrentRenderInfo.Image = image; DirectXRender(CurrentRenderInfo); } }
public static unsafe void QueueCall <T>(this Ipc scope, string method, T frameContent) where T : struct { CallFrameListDescriptor *descriptor = null; //scope.GetObject<CallFrameListDescriptor>("CallFrameListDescriptor:" + method); CallFrameListNode * node = null; //scope.GetObject<CallFrameListNode>("CallFrameListNode:" + descriptor->CallFrameListHead); Luid id = new Luid { Whole = Guid.NewGuid() }; MemoryMappedFile data; //Get a space to store the frame in do { try { data = MemoryMappedFile.CreateNew($"{scope.Name}:CallFrames:{id.Low}", Marshal.SizeOf <T>(), MemoryMappedFileAccess.ReadWrite); //Write frameContent into data break; } catch { id = new Luid { Whole = Guid.NewGuid() }; } } while (true); //Acquire the tail of the call frame list while (Interlocked.CompareExchange(ref node->NextCallFrame, id.Low, 0) != 0) { node = null; //scope.GetObject<CallFrameListNode>("CallFrameListNode:" + node->NextCallFrame); } node = null; //scope.GetObject<CallFrameListNode>("CallFrameListNode:" + id.Low); //Write the current time to the call frame so it may be reclaimed at some point //write Interlocked.Exchange(ref descriptor->CallFrameListHead, id.Low); }
private static void Main(string[] args) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("memfile", 128)) { using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { BinaryWriter writer = new BinaryWriter(stream); int[][] arrInts = new int[5][]; InitializeArray(arrInts); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, arrInts); //ArrayWrite(arrInts, writer); } string[] cmdArgs = new int[] { 121, 32, 321 }.Select(i => i.ToString()).ToArray(); Console.WriteLine("Starting the child process"); // Command line args are separated by a space Process p = Process.Start("ChildProcess.exe", $"memfile {string.Join(" ", cmdArgs)}"); Console.WriteLine("Waiting child to die"); p.WaitForExit(); Console.WriteLine("Child died"); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { BinaryReader reader = new BinaryReader(stream); //ArrayRead(reader); BinaryFormatter bf = new BinaryFormatter(); int[][] arr = (int[][])bf.Deserialize(stream); dynamic arr2 = bf.Deserialize(stream); // Converted to int[] at runtime Console.WriteLine(); Console.WriteLine("Reading child output.."); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public void CreateIPCClassNameMMF(IntPtr hWnd) { if (ipcClassNameMMA != null) return; // Already holding a handle to MMF file. No need to re-write the data try { StringBuilder wndClassNameStr = new StringBuilder(128); if (GetClassName(hWnd, wndClassNameStr, wndClassNameStr.Capacity) != 0 && wndClassNameStr.Length > 0) { byte[] buffer = ASCIIEncoding.ASCII.GetBytes(wndClassNameStr.ToString()); ipcClassNameMMF = MemoryMappedFile.CreateNew("DS4Windows_IPCClassName.dat", 128); ipcClassNameMMA = ipcClassNameMMF.CreateViewAccessor(0, buffer.Length); ipcClassNameMMA.WriteArray(0, buffer, 0, buffer.Length); // The MMF file is alive as long this process holds the file handle open } } catch (Exception) { /* Eat all exceptions because errors here are not fatal for DS4Win */ } }
static void Main(string[] args) { // Open shared memory MemoryMappedFile share_mem = MemoryMappedFile.CreateNew("shared_memory", 1024); MemoryMappedViewAccessor accessor = share_mem.CreateViewAccessor(); // Write data to shared memory string str = "Hello World"; char[] data = str.ToCharArray(); accessor.Write(0, data.Length); accessor.WriteArray <char>(sizeof(int), data, 0, data.Length); // Dispose accessor accessor.Dispose(); // Sleep while (true) { System.Threading.Thread.Sleep(1000); } }
static void Main() { Console.WriteLine("Memory mapped file server started"); using (var file = MemoryMappedFile.CreateNew("myFile", int.MaxValue)) { var bytes = new byte[24]; for (var i = 0; i < bytes.Length; i++) { bytes[i] = (byte)(65 + i); } using (var writer = file.CreateViewAccessor(0, bytes.Length)) { writer.WriteArray <byte>(0, bytes, 0, bytes.Length); } Console.WriteLine("Before exiting run memory mapped file reader"); Console.WriteLine("Press any key to exit ..."); Console.ReadLine(); } }
static void Main() { Test t = new Test() { c1 = '1', c2 = '2', c3 = '3' }; using (MemoryMappedFile file = MemoryMappedFile.CreateNew(null, 1)) using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor()) { accessor.Write <Test>(0L, ref t); t = new Test() { c1 = 'a', c2 = 'b', c3 = 'c' }; accessor.Write <Test>((long)LO.SIZE, ref t); using (StreamReader sr = new StreamReader(file.CreateViewStream(), ASCIIEncoding.ASCII)) { Console.WriteLine(sr.ReadToEnd()); } } }
/// <summary> /// create a single-one provider. /// </summary> /// <returns> /// true if success, otherwise false. /// </returns> public static bool CreateSingleOne() { #if __LINUX__ var _p = Path.Here + Program.MMF_NAME; try { if (Universe._mapped == null) { Universe._mapped ??= File.Create(_p); Universe._mapped?.Lock(0, 0); } return(true); } catch (Exception _e) { Debug.Print(_e.ToString()); Console.WriteLine(_e.Message); return(false); } #elif __WINDOWS__ try { AppSettings.Memory = MemoryMappedFile.CreateNew(Program.MMF_NAME, 10000); var s = AppSettings.Memory.CreateViewStream(); BinaryWriter writer = new BinaryWriter(s); writer.Write(AppSettings.CompanyName); writer.Close(); writer.Dispose(); s.Dispose(); return(true); } catch { return(false); } #else #error Unsupported Platform. #endif }
public DebugListener(AugmentrexContext context) { context.InfoLine("Starting debug message listener..."); _cts = new CancellationTokenSource(); _task = Task.Factory.StartNew(() => { const int BufferSize = 4096; using var mmf = MemoryMappedFile.CreateNew("DBWIN_BUFFER", BufferSize); using var bufReady = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY"); using var dataReady = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY"); while (true) { _cts.Token.ThrowIfCancellationRequested(); bufReady.Set(); if (!dataReady.WaitOne(context.Configuration.DebugListenerInterval)) { continue; } using var stream = mmf.CreateViewStream(0, BufferSize, MemoryMappedFileAccess.Read); using var reader = new BinaryReader(stream); if (reader.ReadUInt32() != context.Game.Id) { continue; } var bytes = reader.ReadBytes(BufferSize - sizeof(int)); var str = Encoding.GetEncoding("euc-kr").GetString(bytes, 0, Array.IndexOf <byte>(bytes, 0)); Log.DebugLine("{0}", str.Substring(0, str.Length - 1)); } }, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
public void VerifyCreateNew(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows) { return; } iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) { VerifyAccess(strLoc, mmf, access, capacity); VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } }
public void InitQueue() { var processName = Process.GetCurrentProcess().ProcessName; var mutex = new Mutex(true, "pathList"); if (Process.GetProcessesByName(processName).Length == 1) { allBmpPaths = rp.ExtractBmpPaths(); var stringAllBmpPaths = string.Join("\n", allBmpPaths); var stringLength = stringAllBmpPaths.Length; interProcessFile = MemoryMappedFile .CreateNew("bmps", stringLength * 2, MemoryMappedFileAccess.ReadWrite); using (var stream = interProcessFile.CreateViewStream()) { var writer = new BinaryWriter(stream); writer.Write(stringAllBmpPaths); } mutex.ReleaseMutex(); return; } interProcessFile = MemoryMappedFile.OpenExisting("bmps"); }
public void Initialize(ListBox listBox) { int size = Marshal.SizeOf(typeof(IdeMessage)); hSharedMemory = MemoryMappedFile.CreateNew(SHARED_MEMORY_NAME, size); hRecvEvent = new EventWaitHandle(false, EventResetMode.AutoReset, RECV_EVENT_NAME); hSendEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SEND_EVENT_NAME); ThreadArg arg = new ThreadArg(); arg.hSendEvent = hSendEvent; arg.hRecvEvent = hRecvEvent; arg.hSharedMemory = hSharedMemory; arg.listBox = listBox; hThread = new BackgroundWorker(); hThread.WorkerSupportsCancellation = true; hThread.DoWork += HThread_DoWork; hThread.RunWorkerAsync(arg); }
public SlaveManager(string arg, int x, int y) { visuals = new List <Visual>(); this._x = x; this._y = y; length = getLength(x, y); mappedFile = MemoryMappedFile.CreateNew(arg, length); displayData = new SlaveData(); displayData.foreColors = new ConsoleColor[x, y]; displayData.backColors = new ConsoleColor[x, y]; displayData.characters = new char[x, y]; //just for now for (int xl = 0; xl < 10; xl++) { for (int yl = 0; yl < 10; yl++) { displayData.foreColors[xl, yl] = ConsoleColor.Red; displayData.backColors[xl, yl] = ConsoleColor.Red; displayData.characters[xl, yl] = arg.ToCharArray()[0]; } } ProcessStartInfo processStartInfo = new ProcessStartInfo { FileName = "RhythmThing.exe", CreateNoWindow = false, UseShellExecute = true, Arguments = $"{arg} {x} {y}" }; _accessor = mappedFile.CreateViewAccessor(); pipe = new NamedPipeServerStream(arg); _slaveProcess = Process.Start(processStartInfo); pipe.WaitForConnection(); _writer = new StreamWriter(pipe); _writer.AutoFlush = true; _aliveWindows.Add(this); }
public void ConnectByPid(Int32 pid) { var securityMemory = new MemoryMappedFileSecurity(); var securityMutex = new MutexSecurity(); var securitySemaphore = new SemaphoreSecurity(); var securityWaiter = new SemaphoreSecurity(); securityMemory.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); securityMutex.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow)); securitySemaphore.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow)); securityWaiter.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow)); this.ipcMemory = MemoryMappedFile.CreateNew($"Global\\dr_analyzer_buffer_{pid}", 76012); this.ipcMemory.SetAccessControl(securityMemory); this.ipcMutex = new Mutex(false, $"Global\\dr_analyzer_mutex_{pid}", out bool createdMutex, securityMutex); this.ipcSentSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_sent_semaphore_{pid}", out bool createdSentSemaphore, securitySemaphore); this.ipcReceivedSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_received_semaphore_{pid}", out bool createdReceivedSemaphore, securitySemaphore); this.ipcWaiterSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_waiter_semaphore_{pid}", out bool createdWaiter, securityWaiter); if (!(createdMutex && createdSentSemaphore && createdReceivedSemaphore && createdWaiter)) { this.FreeSharedObjects(); throw new Exception("One of sync object is already created"); } this.queueSem = new Semaphore(0, 1); this.queueMutex = new Mutex(false); this.isExit = false; this.receiverThread = new Thread(this.ReceiverThreadFunc); this.queueThread = new Thread(this.QueueThreadFunc); this.queueThread.Start(); this.receiverThread.Start(); Injector.InjectByPid(pid); this.Active = true; }
private void Create_MMF(string name) { shMemory = MemoryMappedFile.CreateNew(name, FileSize); int accesorSize = 120; shMemoryAccessor = shMemory.CreateViewAccessor(); for (int i = 0; i < FileSize; i++) { try { Syncronized.sharedMemory.TryAdd(i, new SharedMemory_index_basedWriter(shMemory.CreateViewAccessor(writeCount, accesorSize), writeCount, new EventWaitHandle(false, EventResetMode.ManualReset, ($"{name}mutex{i}")))); Console.WriteLine($"Accessor is ready : Dict index {i} pos {writeCount} handel {name}mutex{i} accessor {accesorSize} "); writeCount += pageCount; accesorSize += pageCount; if (writeCount == FileSize) { break; } } catch (Exception ex) { Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } } //Syncronized.handle = new EventWaitHandle(false, EventResetMode.ManualReset, "testRemoteServer"); //Console.WriteLine("Go baby GO"); //Syncronized.nameDMutex = new Mutex(Syncronized.isMutexOwned, name + "mutex", out Syncronized.isMutexCreated); //Console.WriteLine($"Memory map file {name } has been created : Named mutex and accessor also created"); //Console.WriteLine($"Memory map file size {FileSize} , page count {pageCount}"); //if (!Syncronized.isMutexOwned) Syncronized.nameDMutex.WaitOne(); //Thread.Sleep(10000); //Syncronized.nameDMutex.ReleaseMutex(); }
//------------------------------------------------------------------- // Directory //------------------------------------------------------------------- /// @brief Directory初期化 /// @todo(me) 全体的に例外処理を考慮していないコード。要注意。 public bool InitDirectory() { // 念のため解放 ReleaseDirectory(); // 仮想メモリ(Directory)の作成 /// @todo(me) あまりにも邪悪な例外処理の使い方。なんとかしたい。 MemoryMappedFile tmp_directory; bool already_exists = true; try { tmp_directory = MemoryMappedFile.OpenExisting(kDirectoryName); } catch (FileNotFoundException) { tmp_directory = MemoryMappedFile.CreateNew(kDirectoryName, size_of_directory_); already_exists = false; } // ビューの作成 MemoryMappedViewStream tmp_view_of_directory = tmp_directory.CreateViewStream(); // 最初に共有メモリを作成した場合は0クリアしておく if (!already_exists) { for (int i = 0; i < size_of_directory_; i++) { tmp_view_of_directory.Seek(i, SeekOrigin.Begin); tmp_view_of_directory.WriteByte(0); } } // Mutexの作成 Mutex tmp_mutex_directory = new Mutex(false, kDirectoryMutexName); // メンバ変数に設定 directory_ = tmp_directory; view_of_directory_ = tmp_view_of_directory; mutex_directory_ = tmp_mutex_directory; Trace.WriteLine("****Interprocess: InitDirectory Done"); return true; }
private MemoryMappedInfo CreateTemporaryStorage(long size) { if (size >= SingleFileThreshold) { // Larger blocks are allocated separately var mapName = CreateUniqueName(size); var storage = MemoryMappedFile.CreateNew(mapName, size); return(new MemoryMappedInfo(new ReferenceCountedDisposable <MemoryMappedFile>(storage), mapName, offset: 0, size: size)); } lock (_gate) { // Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted // handle to a memory mapped file is obtained in this section, it must either be disposed before // returning or returned to the caller who will own it through the MemoryMappedInfo. var reference = _weakFileReference.TryAddReference(); if (reference == null || _offset + size > _fileSize) { var mapName = CreateUniqueName(MultiFileBlockSize); var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize); reference = new ReferenceCountedDisposable <MemoryMappedFile>(file); _weakFileReference = new ReferenceCountedDisposable <MemoryMappedFile> .WeakReference(reference); _name = mapName; _fileSize = MultiFileBlockSize; _offset = size; return(new MemoryMappedInfo(reference, _name, offset: 0, size: size)); } else { // Reserve additional space in the existing storage location Contract.ThrowIfNull(_name); _offset += size; return(new MemoryMappedInfo(reference, _name, _offset - size, size)); } } }
static void Main(string[] args) { List <int> a = new List <int>(); a.Add(1); a.Add(5); a.Add(4); a.Add(3); MemoryMappedFile dupa = MemoryMappedFile.CreateNew("14", 65000 * 4); byte[] tmp = new byte[65000 * 4]; //using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("14", 10000)) //{ var binFormater = new BinaryFormatter(); var mStream = new MemoryStream(); binFormater.Serialize(mStream, a); Stopwatch w = Stopwatch.StartNew(); using (MemoryMappedViewStream stream = dupa.CreateViewStream()) { BinaryWriter writer = new BinaryWriter(stream); //Console.WriteLine(mStream.ToArray().Length); //writer.Write(mStream.ToArray()); //writer.Write(tmp); for (int i = 0; i < 65000; i++) { writer.Write(8 + i); } //writer.Write(1); //writer.Write(222); } w.Stop(); //} Console.ReadKey(); }
private void CreateNewExtent() { int newFileId = this.fileId; this.fileId++; this.extentName = string.Format(FileNameFormat, this.fileName, newFileId); // create a new file first, just in case anybody is reading MemoryMappedFile newMMF; if (!this.IsVolatile) { this.extentName = System.IO.Path.Combine(this.path, this.extentName); using (var file = File.Open(this.extentName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) { newMMF = MemoryMappedFile.CreateFromFile(file, null, this.extentSize, MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable, false); } } else { newMMF = MemoryMappedFile.CreateNew(this.extentName, this.extentSize); } // store the id of the new file in the old file and close it if (this.mappedFile != null) { *(int *)this.freePointer = -newFileId; // end of file marker this.CloseCurrent(false); } // re-initialize this.mappedFile = newMMF; this.view = this.mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite); this.view.SafeMemoryMappedViewHandle.AcquirePointer(ref this.startPointer); this.freeSpace = this.extentSize - sizeof(int); this.freePointer = this.startPointer; *((uint *)this.freePointer) = 0; }
private MemoryMappedFile CreateMemoryMappedFile(int port, string fileName) { _logger.Always($"Trying to expose GRPC port {port} at memory mapped file '{fileName}'"); #if PLATFORM_WIN var file = MemoryMappedFile.CreateNew( fileName, FileSize, MemoryMappedFileAccess.ReadWrite); #else var file = MemoryMappedFile.CreateFromFile( fileName, FileMode.Create, null, FileSize, MemoryMappedFileAccess.ReadWrite); #endif try { using (var stream = file.CreateViewStream()) { using (var writer = new StreamWriter(stream)) { writer.Write(port); } } } catch { file.Dispose(); throw; } _logger.Always($"Memory mapped file '{fileName}' successfully created"); return(file); }