Action <string> dataAction;//数据委托 ///<summary> /// 初始化共享内存数据 创建一个共享内存 ///</summary> public void Init(Action <string> _dataAction, IPCType type, IPCType addrtype) { dataAction = _dataAction; m_Write = new Semaphore(1, 1, IPCName.GetWriteMapName(type)); //开始的时候有一个可以写 m_Read = new Semaphore(0, 1, IPCName.GetReadMapName(type)); //没有数据可读 //mapLength = 10240000; IntPtr hFile = new IntPtr(INVALID_HANDLE_VALUE); handle = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, IPCName.mapLength, IPCName.GetshareMemoryName(type)); addr = MapViewOfFile(handle, IPCName.GetshareAddress(addrtype), 0, 0, 0); //handle = OpenFileMapping(0x0002, 0, "shareMemory"); //addr = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0); threadRed = new Thread(new ThreadStart(ReceiveData)); threadRed.Start(); }
private IntPtr addr; //共享内存地址 //uint mapLength=10240000; //共享内存长 //Thread threadRed; public void WriteData(string data, IPCType type, IPCType addrtype) { try { m_Write = Semaphore.OpenExisting(IPCName.GetWriteMapName(type)); m_Read = Semaphore.OpenExisting(IPCName.GetReadMapName(type)); handle = OpenFileMapping(FILE_MAP_WRITE, 0, IPCName.GetshareMemoryName(type)); addr = MapViewOfFile(handle, IPCName.GetshareAddress(addrtype), 0, 0, 0); m_Write.WaitOne(); byte[] sendStr = Encoding.Default.GetBytes(data + '\0'); //如果要是超长的话,应另外处理,最好是分配足够的内存 if (sendStr.Length < IPCName.mapLength) { Copy(sendStr, addr); } m_Read.Release(); } catch { //throw new Exception("不存在系统信号量!"); } }