How to detect if a MemoryMappedFile is in use

烈酒焚心 提交于 2021-02-07 07:38:39

问题


In C# 4.0, MemoryMappedFile has several factory methods: CreateFromFile, CreateNew, CreateOrOpen, or OpenExisting. I need to open the MemoryMappedFile if it exists, and if not, create it from a file. My code to open the memory map looks like this:

try
{
    map = MemoryMappedFile.OpenExisting(
        MapName,
        MemoryMappedFileRights.ReadWrite
        | MemoryMappedFileRights.Delete);
}
catch (FileNotFoundException)
{
    try
    {
        stream = new FileStream(
            FileName,
            FileMode.OpenOrCreate,
            FileAccess.ReadWrite,
            FileShare.Read | FileShare.Delete);
        map = MemoryMappedFile.CreateFromFile(
            stream, MapName, length + 16,
            MemoryMappedFileAccess.ReadWrite,
            null,
            HandleInheritability.None,
            false);
    }
    catch
    {
        if (stream != null)
            stream.Dispose();
        stream = null;
    }
}

It pretty much works the way I want it to, but it ends up throwing an exception on OpenExisting way too often. Is there a way to check whether the MemoryMappedFile actually exists before I try to do the OpenExisting call? Or do I have to deal with the exception every single time?

Also, is there a way to find out if the current handle is the last one to have the MemoryMappedFile open, to determine if the file will be closed when the current handle is disposed?


回答1:


You can use MemoryMappedFile.CreateOrOpen:

map = MemoryMappedFile.CreateOrOpen(
                MapName, length + 16,
                MemoryMappedFileAccess.ReadWrite, 
                MemoryMappedFileOptions.None, null, HandleInheritability.None);



回答2:


See Han Passant's comment under the original question for accepted answer. Since I can't mark it as accepted, I'll just refer to it here and mark this as accepted.



来源:https://stackoverflow.com/questions/9422082/how-to-detect-if-a-memorymappedfile-is-in-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!