共享内存定义
共享内存(Shared Memory)是一种进程间通信(IPC)机制,通过它,多个进程可以访问同一块内存,从而实现高效的数据共享和通信。这种方式比其他IPC机制(如管道、消息队列)更高效,因为它避免了数据在进程间的复制。
帮助类编写
public class SharedMemoryHelper
{
private string memoryName;
private string mutexName;
private Mutex mutex;
public SharedMemoryHelper(string memoryName, string mutexName)
{
this.memoryName = memoryName;
this.mutexName = mutexName;
this.mutex = new Mutex(false, mutexName);
}
public bool IsSharedMemoryCreated()
{
try
{
MemoryMappedFile.OpenExisting(memoryName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
public void WriteToSharedMemory(string message)
{
mutex.WaitOne();
try
{
MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(memoryName, 1024);
MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
byte[] clearBuffer = new byte[1024];
accessor.WriteArray(0, clearBuffer, 0, clearBuffer.Length);
byte[] buffer = Encoding.UTF8.GetBytes(message);
accessor.WriteArray(0, buffer, 0, buffer.Length);
}
finally
{
mutex.ReleaseMutex();
}
}
public string ReadFromSharedMemory()
{
mutex.WaitOne();
try
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(memoryName);
MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
byte[] buffer = new byte[1024];
accessor.ReadArray(0, buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer).TrimEnd('\0');
}
catch (FileNotFoundException)
{
throw new InvalidOperationException("找不到共享内存文件.");
}
finally
{
mutex.ReleaseMutex();
}
}
}
使用方法
private readonly SharedMemoryHelper _SharedMemory;
public MainWindowViewModel()
{
_SharedMemory = new SharedMemoryHelper(MemoryName, MutexName);
_SharedMemory.WriteToSharedMemory(WriteMessage);
if (_SharedMemory.IsSharedMemoryCreated())
{
Test = JsonConvert.DeserializeObject<Test>(ReadMessage);
}
else
{
MessageBox.Show("读取不到内存文件!");
}
}
2024/6/6
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » C# 共享内存
发表评论 取消回复