Inheritance: System.IO.UnmanagedMemoryStream
Ejemplo n.º 1
0
		private void CreateFileStreams()
		{
			if (_file != null || _fileStream != null)
				throw new InvalidOperationException();

			_file = MemoryMappedFile.CreateFromFile(FileName);
			_fileStream = _file.CreateViewStream();
		}
        private void InitializeMemoryMap()
        {
            var mmf = MemoryMappedFile.CreateOrOpen(DATA_FILE, 1024 * 10);
            var view = mmf.CreateViewStream();

            MappedFile = mmf;
            ViewStream = view;
            LinkDataSize = Marshal.SizeOf(typeof(LinkData));
        }
Ejemplo n.º 3
0
        public MappedFileBuffer(byte[] data)
        {
            _file = MemoryMappedFile.CreateNew(Guid.NewGuid().ToString(), data.Length);
            _stream = _file.CreateViewStream();
            _stream.Write(data, 0, data.Length);
            
			//File.WriteAllBytes(_file.Name, data);
			_size = (uint)data.Length;
		}
Ejemplo n.º 4
0
 public SharedRingBuffer(string name, int size)
 {
     _size = size;
     _memory = MemoryMappedFile.CreateOrOpen(name, size + 1);
     _memoryStream = _memory.CreateViewStream();
     _writer = new BinaryWriter(_memoryStream);
     _reader = new BinaryReader(_memoryStream);
     _writer.Write(char.MinValue);
 }
Ejemplo n.º 5
0
 public HeurFacade(string mutName, string mmfName, int RegIterations)
 {
     // Time of listening before register
     this.Luogo1 = new Dictionary<string, Network>();
     this.threshold = RegIterations;
     this.mut = Mutex.OpenExisting(mutName); ;
     this.mmf = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.FullControl, HandleInheritability.None);
     this.stream = mmf.CreateViewStream(0, MappedFileDimension, MemoryMappedFileAccess.Read);
 }
Ejemplo n.º 6
0
        public MemoryMappedReadWriteContext(MemoryMappedViewAccessor viewAccessor,
            MemoryMappedViewStream viewStream, Mutex accessMutex, bool lockOnCreate)
        {
            ViewAccessor = viewAccessor;
            ViewStream = viewStream;
            _accessMutex = accessMutex;

            if (lockOnCreate)
                Lock();
        }
Ejemplo n.º 7
0
	public byte Read(long T,MemoryMappedViewStream stream){

				byte[] buffer = new byte[1];
                		BinaryReader reader = new BinaryReader(stream);
     				try{reader.Read(buffer,(int)Math.Floor(T/8.0),1);}
				catch{return default(byte);}
				
				return buffer[0];
           		
			
	}
Ejemplo n.º 8
0
        public TextureDesc(System.IO.MemoryMappedFiles.MemoryMappedViewStream mmvs)
        {
            var br = new BinaryReader(mmvs);

            SharedHandle = br.ReadUInt32();
            Width        = br.ReadUInt32();
            Height       = br.ReadUInt32();
            Format       = br.ReadUInt32();
            Usage        = br.ReadUInt32();
            Description  = br.ReadBytes(256);
        }
 public MemoryMappedFileMessageSender(string name)
 {
     _file = MemoryMappedFile.CreateOrOpen(name, SizeOfFile);
     _bytesWrittenAccessor = _file.CreateViewAccessor(0, SizeOfInt32);
     _messageCompletedAccessor = _file.CreateViewAccessor(SizeOfInt32, SizeOfBool);
     _stream = _file.CreateViewStream(SizeOfInt32 + SizeOfBool + SizeOfBool, SizeOfStream);
     _messageSendingEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_MessageSending");
     _messageReadEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_MessageRead");
     _messageCancelledEvent = new EventWaitHandle(false, EventResetMode.ManualReset, name + "_MessageCancelled");
     _bytesWrittenEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_BytesWritten");
     _bytesReadEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_BytesRead");
 }
        /// @brief コンストラクタ
        public Interprocess()
        {
            directory_ = null;
            view_of_directory_ = null;
            mutex_directory_ = null;
            message_ = null;
            view_of_message_ = null;
            mutex_message_ = null;

            size_of_directory_ = Marshal.SizeOf(typeof(Directory));
            size_of_message_ = Marshal.SizeOf(typeof(Message));

            Trace.WriteLine("****Interprocess: NEW");
        }
Ejemplo n.º 11
0
 //---------------------------------------------------------------------------------------
 // Construction
 //---------------------------------------------------------------------------------------
 public SharedMemory(bool create, int cbBuffer, string uniquifier)
 {
     this.theLock            = new object();
     this.initialized        = false;
     this.create             = create;
     this.disposed           = false;
     this.cbBuffer           = cbBuffer;
     this.uniquifier         = uniquifier;
     this.Mutex              = null;
     this.BufferChangedEvent = null;
     this.MemoryMappedFile   = null;
     this.MemoryViewStream   = null;
     this.Reader             = null;
     this.Writer             = null;
 }
Ejemplo n.º 12
0
        protected void Dispose(bool disposing)
        {
            if (this.disposed)
            {
                return;
            }

            if (disposing)
            {
                this.stream.Dispose();
            }

            this.stream = null;

            this.disposed = true;
        }
        public ConnectImpl()
        {
            _onDataUpdatedEvent = new EventWaitHandle(true, EventResetMode.ManualReset, OnDataUpdatedEventName);
            _onWriteLockMutex = new Mutex(false, OnWriteLockMutexName);

            using (GetLock())
            {
                try
                {
                    _memoryMappedFile = MemoryMappedFile.OpenExisting(MemoryMappedFileName);
                }
                catch (FileNotFoundException)
                {
                    _memoryMappedFile = MemoryMappedFile.CreateNew(MemoryMappedFileName, MemoryMappedFileSize);
                }

                _memoryMappedViewAccessor = _memoryMappedFile.CreateViewAccessor();
                _memoryMappedViewStream = _memoryMappedFile.CreateViewStream();
                _memoryMappedViewHandle = _memoryMappedViewStream.SafeMemoryMappedViewHandle.DangerousGetHandle();
            }
        }
Ejemplo n.º 14
0
 public ParityChange(Parity parity, Config config, UInt32 startBlock, UInt32 lengthInBlocks)
 {
     this.parity = parity;
       this.startBlock = startBlock;
       tempDir = config.TempDir;
       writingToMMF = true;
       UInt32 maxMMFBlocks = Parity.LengthInBlocks((long)config.MaxTempRAM * 1024 * 1024);
       UInt32 mmfBlocks = (lengthInBlocks < maxMMFBlocks) ? lengthInBlocks : maxMMFBlocks;
       try {
     mmf = MemoryMappedFile.CreateNew("disparity.tmp", (long)mmfBlocks * Parity.BLOCK_SIZE);
     mmfStream = mmf.CreateViewStream();
       }
       catch (Exception e) {
     LogFile.Log("Could not create memory mapped file: " + e.Message);
     // We'll use a temp file only
     mmf = null;
     mmfStream = null;
     writingToMMF = false;
       }
       tempFileStream = null;
       parityBlock = new ParityBlock(parity);
       block = startBlock;
 }
Ejemplo n.º 15
0
        private void Read(MemoryMappedViewStream stream)
        {                        
            try
            {
                var serializer = new BinaryFormatter();

                stream.Position = 0;
                var timestamp = DateTime.Now;
                AudioDataDTO result = null;

                try {
                    result = serializer.Deserialize(stream) as AudioDataDTO;
                } catch (SerializationException)
                {
                    if (lastGuid != Guid.Empty) {
                        Console.WriteLine("Error deserializing; resetting listener...");
                        lastGuid = Guid.Empty;
                    }                    
                }

                if (result == null || result.Guid == lastGuid)
                {
                    Thread.Sleep(1); // Drops typical CPU usage while 'idle' from 18-23% to <1%
                    return;
                }

                lastGuid = result.Guid;                
                var diff = timestamp - result.Timestamp;                

                Console.WriteLine("Message in; delay: " + diff.TotalMilliseconds);
                Console.WriteLine(result.ToString());
                                
            } catch (Exception ex) {
                Console.WriteLine("Error: " + ex.Message);
            }                        
        }
Ejemplo n.º 16
0
        private byte[] GetBufferFromMapped(long offset, int length)
        {
            var baseIdx = CalcIndexBase(offset);
            if (baseIdx != _stream.PointerOffset)
                _stream = _mapped.CreateViewStream(baseIdx, MemBlockSize);

            var start = offset - baseIdx;
            var len = (int)(_stream.Length - start);
            len = len < length ? len : length;

            var buff = new byte[len];
            _stream.Position = start;
            var count = _stream.Read(buff, 0, len);
            if (len == count)
                return buff;

            var temp = new byte[count];
            Array.Copy(buff, 0, temp, 0, count);

            return temp;
        }
Ejemplo n.º 17
0
        public void WriteMappedToStream(Stream stream, long offset, long length, bool writeToMapped)
        {
            while (length > 0)
            {
                var source = writeToMapped ? _stream : _editBuffer;
                if (writeToMapped)
                {
                    var idxBase = CalcIndexBase(offset);
                    if (idxBase != _stream.PointerOffset)
                    {
                        _stream = _mapped.CreateViewStream(idxBase, MemBlockSize);
                        source = _stream;
                    }
                    _stream.Position = offset - _stream.PointerOffset;
                }
                else
                    _editBuffer.Position = offset;

                var len = length > BufferSize ? BufferSize : length;
                var buffer = new byte[len];
                var count = source.Read(buffer, 0, (int)len);
                if (count <= 0)
                    break;

                stream.Write(buffer, 0, count);
                length -= count;
                offset += count;
            }
        }
Ejemplo n.º 18
0
Archivo: Flute.cs Proyecto: kidaa/Pulse
 public FluteWriter(Flute flute, long offset = 0, long size = 0)
 {
     _flute = flute;
     _output = _flute._mmf.CreateViewStream(offset, size, MemoryMappedFileAccess.Write);
     Interlocked.Increment(ref _flute._writers);
 }
 /// @brief Message解放
 void ReleaseMessage()
 {
     if (mutex_message_ != null) {
       mutex_message_.Dispose();
       mutex_message_ = null;
     }
     if (view_of_message_ != null) {
       view_of_message_.Dispose();
       view_of_message_ = null;
     }
     if (message_ != null) {
       message_.Dispose();
       message_ = null;
     }
 }
 //-------------------------------------------------------------------
 // Private
 //-------------------------------------------------------------------
 /// @brief Directory解放
 void ReleaseDirectory()
 {
     if (mutex_directory_ != null) {
       mutex_directory_.Dispose();
       mutex_directory_ = null;
     }
     if (view_of_directory_ != null) {
       view_of_directory_.Dispose();
       view_of_directory_ = null;
     }
     if (directory_ != null) {
       directory_.Dispose();
       directory_ = null;
     }
 }
        //-------------------------------------------------------------------
        // 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;
        }
Ejemplo n.º 22
0
        public void RunProcess(Action<Action<StringDictionary>> process, bool isService)
        {
            var key = Guid.NewGuid().GetHashCode().ToString("X");
            var processMgmt = new AutoResetEvent(false);
            var queueMgmt = new AutoResetEvent(false);
            var environmentKeyRead = new AutoResetEvent(false);
            var handles = new List<WaitHandle> { processMgmt };

            string @namespace = isService ? "Global" : "Local";

            _memoryManager.Initialise(@namespace, key);

            _profilerRequestsInformation = new EventWaitHandle(false, EventResetMode.ManualReset,
                @namespace + @"\OpenCover_Profiler_Communication_SendData_Event_" + key);
            _informationReadyForProfiler = new EventWaitHandle(false, EventResetMode.ManualReset,
                @namespace + @"\OpenCover_Profiler_Communication_ReceiveData_Event_" + key);
            _informationReadByProfiler = new EventWaitHandle(false, EventResetMode.ManualReset,
                @namespace + @"\OpenCover_Profiler_Communication_ChunkData_Event_" + key);

            handles.Add(_profilerRequestsInformation);

            _messageQueue = new ConcurrentQueue<byte[]>();

            using (var mmfComms = MemoryMappedFile.CreateNew(@namespace + @"\OpenCover_Profiler_Communication_MemoryMapFile_" + key, maxMsgSize))
            using (_streamAccessorComms = mmfComms.CreateViewStream(0, maxMsgSize, MemoryMappedFileAccess.ReadWrite))
            {
                ThreadPool.QueueUserWorkItem((state) =>
                {
                    try
                    {
                        process(dictionary =>
                        {
                            if (dictionary == null) return;
                            dictionary[@"OpenCover_Profiler_Key"] = key;
                            dictionary[@"OpenCover_Profiler_Namespace"] = @namespace;
                            dictionary["Cor_Profiler"] = "{1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8}";
                            dictionary["Cor_Enable_Profiling"] = "1";
                            dictionary["CoreClr_Profiler"] = "{1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8}";
                            dictionary["CoreClr_Enable_Profiling"] = "1";
                            environmentKeyRead.Set();
                        });
                    }
                    finally
                    {
                        processMgmt.Set();
                    }
                });

                ThreadPool.QueueUserWorkItem((state) =>
                {
                    while (true)
                    {
                        byte[] data;
                        while (!_messageQueue.TryDequeue(out data))
                            Thread.Yield();

                        if (data.Length == 0)
                        {
                            _messageHandler.Complete();
                            queueMgmt.Set();
                            return;
                        }

                        _persistance.SaveVisitData(data);
                    }
                });

                // wait for the environment key to be read
                if (WaitHandle.WaitAny(new[] { environmentKeyRead }, new TimeSpan(0, 0, 0, 10)) == -1)
                    return;

                _dataCommunication = new byte[maxMsgSize];
                var pinnedComms = GCHandle.Alloc(_dataCommunication, GCHandleType.Pinned);
                try
                {
                    ProcessMessages(handles, pinnedComms);
                }
                finally
                {
                    pinnedComms.Free();
                }

                queueMgmt.WaitOne();
            }
        }
Ejemplo n.º 23
0
 /// Message解放
 private void ReleaseMessage()
 {
     if (this.mutexMessage != null) {
       this.mutexMessage.Dispose();
       this.mutexMessage = null;
     }
     if (this.viewOfMessage != null) {
       this.viewOfMessage.Dispose();
       this.viewOfMessage = null;
     }
     if (this.message != null) {
       this.message.Dispose();
       this.message = null;
     }
 }
        //-------------------------------------------------------------------
        // Message
        //-------------------------------------------------------------------
        /// @brief Message初期化
        public bool InitMessage(UInt32 process_id)
        {
            // 念のため解放
            ReleaseMessage();

            // 仮想メモリの名前
            string message_name = kMessageNamePrefix + process_id;

            // 仮想メモリ(Message<process_id>)の作成
            MemoryMappedFile tmp_message;
            bool already_exists = true;
            try {
              tmp_message = MemoryMappedFile.OpenExisting(message_name);
            } catch (FileNotFoundException) {
              tmp_message =
              MemoryMappedFile.CreateNew(message_name, size_of_message_);
              already_exists = false;
            }

            // ビューの作成
            MemoryMappedViewStream tmp_view_of_message =
            tmp_message.CreateViewStream();

            // 最初に共有メモリを作成した場合は0クリアしておく
            if (!already_exists) {
              for (int i = 0; i < size_of_message_; i++) {
            tmp_view_of_message.Seek(i, SeekOrigin.Begin);
            tmp_view_of_message.WriteByte(0);
              }
            }

            // Mutexの名前
            string message_mutex_name = kMessageMutexNamePrefix + process_id;

            // Mutexの作成
            Mutex tmp_mutex_message = new Mutex(false, message_mutex_name);

            // メンバ変数に設定
            message_ = tmp_message;
            view_of_message_ = tmp_view_of_message;
            mutex_message_ = tmp_mutex_message;

            Trace.WriteLine("****Interprocess: InitMessage Done");
            return true;
        }
Ejemplo n.º 25
0
        //===================================================================
        // Message
        //===================================================================
        /// Message初期化
        public bool InitMessage(UInt32 processID)
        {
            // 念のため解放
            this.ReleaseMessage();

            // 仮想メモリの名前
            string messageName = MessageNamePrefix + processID;

            // 仮想メモリ(Message<ProcessID>)の作成
            MemoryMappedFile tmpMessage;
            bool alreadyExists = true;
            try {
              tmpMessage = MemoryMappedFile.OpenExisting(messageName);
            } catch (FileNotFoundException) {
              tmpMessage =
              MemoryMappedFile.CreateNew(messageName, this.sizeOfMessage);
              alreadyExists = false;
            }

            // ビューの作成
            MemoryMappedViewStream tmpViewOfMessage =
            tmpMessage.CreateViewStream();

            // 最初に共有メモリを作成した場合は0クリアしておく
            if (!alreadyExists) {
              for (int i = 0; i < this.sizeOfMessage; i++) {
            tmpViewOfMessage.Seek(i, SeekOrigin.Begin);
            tmpViewOfMessage.WriteByte(0);
              }
            }

            // Mutexの名前
            string messageMutexName = MessageMutexNamePrefix + processID;

            // Mutexの作成
            Mutex tmpMutexMessage = new Mutex(false, messageMutexName);

            // フィールドに設定
            this.message = tmpMessage;
            this.viewOfMessage = tmpViewOfMessage;
            this.mutexMessage = tmpMutexMessage;

            Trace.WriteLine("****Interprocess: InitMessage Done");
            return true;
        }
Ejemplo n.º 26
0
 /// Directory解放
 private void ReleaseDirectory()
 {
     if (this.mutexDirectory != null) {
       this.mutexDirectory.Dispose();
       this.mutexDirectory = null;
     }
     if (this.viewOfDirectory != null) {
       this.viewOfDirectory.Dispose();
       this.viewOfDirectory = null;
     }
     if (this.directory != null) {
       this.directory.Dispose();
       this.directory = null;
     }
 }
Ejemplo n.º 27
0
        //===================================================================
        // 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;
        }
Ejemplo n.º 28
0
        //===================================================================
        // コンストラクタ/デストラクタ
        //===================================================================
        /// コンストラクタ
        public Interprocess()
        {
            this.directory = null;
            this.viewOfDirectory = null;
            this.mutexDirectory = null;
            this.message = null;
            this.viewOfMessage = null;
            this.mutexMessage = null;

            this.shutdownEvent = null;

            this.directoryType = typeof(Directory);
            this.messageType = typeof(Message);

            this.sizeOfDirectory = Marshal.SizeOf(this.directoryType);
            this.sizeOfMessage = Marshal.SizeOf(this.messageType);

            Trace.WriteLine("****Interprocess: NEW");
        }
Ejemplo n.º 29
0
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public bool CreateServer()
        {
            try
            {
                _memoryMappedFile = MemoryMappedFile.CreateOrOpen(_smKeyStoreName, _smKeyStoreSize);
                _reader = _memoryMappedFile.CreateViewAccessor(0, _smKeyStoreSize, MemoryMappedFileAccess.ReadWrite);
                _writer = _memoryMappedFile.CreateViewStream(0, _smKeyStoreSize, MemoryMappedFileAccess.ReadWrite);
                _keystoreLock = new Mutex(true, LageantLock, out _isLocked);
            }
            catch
            {
                return false;
            }

            return true;
        }
Ejemplo n.º 30
0
        public DumpFileMemoryReader(string dumpFilePath)
        {
            bool dispose = true;
            FileStream fileStream = null;
            MemoryMappedFile memoryMappedFile = null;
            MemoryMappedViewStream stream = null;

            try
            {
                fileStream = new FileStream(dumpFilePath, FileMode.Open, FileAccess.Read);
                memoryMappedFile = MemoryMappedFile.CreateFromFile(fileStream, Guid.NewGuid().ToString(), fileStream.Length, MemoryMappedFileAccess.Read, new MemoryMappedFileSecurity(), HandleInheritability.Inheritable, false);
                stream = memoryMappedFile.CreateViewStream(0, fileStream.Length, MemoryMappedFileAccess.Read);

                stream.SafeMemoryMappedViewHandle.AcquirePointer(ref basePointer);
                IntPtr streamPointer = IntPtr.Zero;
                uint streamSize = 0;
                MINIDUMP_DIRECTORY directory = new MINIDUMP_DIRECTORY();

                if (!MiniDumpReadDumpStream((IntPtr)basePointer, MINIDUMP_STREAM_TYPE.Memory64ListStream, ref directory, ref streamPointer, ref streamSize))
                    throw new Exception("Unable to read mini dump stream");

                var data = (MINIDUMP_MEMORY64_LIST)Marshal.PtrToStructure(streamPointer, typeof(MINIDUMP_MEMORY64_LIST));
                ulong lastEnd = data.BaseRva;

                ranges = new MemoryLocation[data.NumberOfMemoryRanges];
                for (int i = 0; i < ranges.Length; i++)
                {
                    var descriptor = (MINIDUMP_MEMORY_DESCRIPTOR64)Marshal.PtrToStructure(streamPointer + sizeof(MINIDUMP_MEMORY64_LIST) + i * sizeof(MINIDUMP_MEMORY_DESCRIPTOR64), typeof(MINIDUMP_MEMORY_DESCRIPTOR64));
                    ranges[i] = new MemoryLocation()
                    {
                        MemoryStart = descriptor.StartOfMemoryRange,
                        MemoryEnd = descriptor.StartOfMemoryRange + descriptor.DataSize,
                        FilePosition = lastEnd,
                    };
                    lastEnd += descriptor.DataSize;
                }

                int newEnd = 0;
                for (int i = 1; i < ranges.Length; i++)
                    if (ranges[i].MemoryStart == ranges[newEnd].MemoryEnd)
                        ranges[newEnd].MemoryEnd = ranges[i].MemoryEnd;
                    else
                        ranges[++newEnd] = ranges[i];
                newEnd++;
                Array.Resize(ref ranges, newEnd);
                finder = new MemoryRegionFinder(ranges.Select(r => new MemoryRegion { BaseAddress = r.MemoryStart, MemoryEnd = r.MemoryEnd }).ToArray());
                dispose = false;
            }
            finally
            {
                if (dispose)
                {
                    stream.SafeMemoryMappedViewHandle.ReleasePointer();
                    if (stream != null)
                    {
                        stream.Dispose();
                    }

                    if (memoryMappedFile != null)
                    {
                        memoryMappedFile.Dispose();
                    }

                    if (fileStream != null)
                    {
                        fileStream.Dispose();
                    }
                }
                else
                {
                    this.fileStream = fileStream;
                    this.stream = stream;
                    this.memoryMappedFile = memoryMappedFile;
                }
            }
        }
        public SharedMemory(string name, IntPtr size)
        {
            mmf = MemoryMappedFile.OpenExisting(name + "_CONNECT_DATA");

            mmva = mmf.CreateViewAccessor();
            if (mmf.SafeMemoryMappedFileHandle.IsInvalid)
                throw new MySqlException("Cannot open file mapping " + name);
            mmvs = mmf.CreateViewStream(0L, size.ToInt64());
            mmva = mmf.CreateViewAccessor(0L, size.ToInt64());
        }