【问题标题】:Prevent memory leaks on reinitialise防止重新初始化时的内存泄漏
【发布时间】:2015-05-23 08:43:44
【问题描述】:

我有一个类可以打开内存映射文件,读写它:

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)重新初始化,我想知道 - 这样做是否安全这样一来,互斥量是否会导致内存泄漏或不可预测的行为?

【问题讨论】:

标签: c# memory-leaks mutex memory-mapped-files


【解决方案1】:

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

当您处理非托管资源和一次性对象时,最好正确实现 IDispose 接口。 Here is some more information.

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2010-09-21
    • 2015-02-05
    • 1970-01-01
    相关资源
    最近更新 更多