共享内存定义

共享内存(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

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部