繁体   English   中英

防止重新初始化时发生内存泄漏

[英]Prevent memory leaks on reinitialise

我有一个可以打开内存映射文件,对其进行读写的类:

public class Memory
{
    protected bool _lock;
    protected Mutex _locker;
    protected MemoryMappedFile _descriptor;
    protected MemoryMappedViewAccessor _accessor;

    public void Open(string name, int size)
    {
        _descriptor = MemoryMappedFile.CreateOrOpen(name, size);
        _accessor = _descriptor.CreateViewAccessor(0, size, MemoryMappedFileAccess.ReadWrite);
        _locker = new Mutex(true, Guid.NewGuid().ToString("N"), out _lock);
    }

    public void Close()
    {
        _accessor.Dispose();
        _descriptor.Dispose();
        _locker.Close();
    }

    public Byte[] Read(int count, int index = 0, int position = 0)
    {
        Byte[] bytes = new Byte[count];
        _accessor.ReadArray<Byte>(position, bytes, index, count);
        return bytes;
    }

    public void Write(Byte[] data, int count, int index = 0, int position = 0)
    {
        _locker.WaitOne();
        _accessor.WriteArray<Byte>(position, data, index, count);
        _locker.ReleaseMutex();
    }

通常我用这种方式:

var data = new byte[5];
var m = new Memory();
m.Open("demo", sizeof(data));
m.Write(data, 5);
m.Close();

我想实现某种延迟加载以打开文件,并且仅在准备好向其中写入内容时才想打开文件,例如:

    public void Write(string name, Byte[] data, int count, int index = 0, int position = 0)
    {
        _locker.WaitOne();
        Open(name, sizeof(byte) * count); // Now I don't need to call Open() before the write
        _accessor.WriteArray<Byte>(position, data, index, count);
        _locker.ReleaseMutex();
    }

问题 :当我多次(循环)调用“ Write”方法时,它将导致成员变量(如_locker)重新初始化,我想知道-这样安全吗,是否会导致内存泄漏或不可预测互斥的行为?

如果使用锁在write方法中打开,则在释放互斥锁之前可以安全关闭。

当您处理非托管资源和一次性对象时,最好正确地实现IDispose接口。 这是更多信息

然后可以在using子句中初始化Memory实例

using (var m = new Memory())
{
// Your read write
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM