簡體   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