在 C# 中处理内存映射文件的正确方法
Correct way to dispose memory mapped files in C#
我有以下测试代码:
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)
失败。
释放内存映射文件占用的所有资源的正确方法是什么?
之后
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
你需要打电话给
accessor.SafeMemoryMappedViewHandle.ReleasePointer();
用于清理。
我有以下测试代码:
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)
失败。
释放内存映射文件占用的所有资源的正确方法是什么?
之后
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
你需要打电话给
accessor.SafeMemoryMappedViewHandle.ReleasePointer();
用于清理。