在C#中配置内存映射文件的正确方法

时间:2015-09-03 09:13:04

标签: c# dispose memory-mapped-files

我有以下测试代码:

const string filePath = @"c:\tests\mmap.bin";
const long k64 = 64 * 1024;

// create mmap file and accessor, then adquire pointer 
var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
fileStream.SetLength(k64);

var mmap = MemoryMappedFile.CreateFromFile(fileStream, null, fileStream.Length,
    MemoryMappedFileAccess.ReadWrite,
    null, HandleInheritability.None, true);

var accessor = mmap.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite);
byte* pointer = null;
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);


// dispose accessor,  mmap file and stream
accessor.SafeMemoryMappedViewHandle.Close();
accessor.Dispose();
mmap.SafeMemoryMappedFileHandle.Close();
mmap.Dispose();
fileStream.Dispose();

// This causes UnauthorizedAccessException: 
// Access to the path 'c:\tests\mmap.bin' is denied
File.Delete(filePath);

创建或打开c:\tests\mmap.bin,将其长度设置为64Kb,内存映射它,然后尝试释放所有资源。但并非所有资源都已发布,File.Delete(filePath)失败。

哪种方法可以释放内存映射文件所拥有的所有资源?

1 个答案:

答案 0 :(得分:3)

accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);

你需要打电话

accessor.SafeMemoryMappedViewHandle.ReleasePointer();

进行清理。