MemoryMappedFile 内存映射文件 msdn

http://msdn.microsoft.com/zh-cn/library/dd997372%28v=vs.110%29.aspx

 

内存映射文件

.NET Framework 4.5
其他版本
1(共 1)对本文的评价是有帮助 - 评价此主题

 

内存映射文件包含虚拟内存中文件的内容。 利用文件与内存空间之间的映射,应用程序(包括多个进程)可以通过直接在内存中进行读写来修改文件。 Managing Memory-Mapped Files in Win32 in the MSDN Library.‘ data-guid="10d58d1c8d6dca5f7b3bd73658bebbe6">从 .NET Framework 4开始,可以使用托管代码按照本机Windows函数访问内存映射文件的方式来访问内存映射文件,如 MSDN Library 中的Managing Memory-Mapped Files in Win32 (管理 Win32 中的内存映射文件)中所述。

有两种类型的内存映射文件:

  • 持久内存映射文件

    持久文件是与磁盘上的源文件关联的内存映射文件。 在最后一个进程使用完此文件后,数据将保存到磁盘上的源文件中。 这些内存映射文件适合用来处理非常大的源文件。

  • 非持久内存映射文件

    非持久文件是未与磁盘上的源文件关联的内存映射文件。 当最后一个进程使用完此文件后,数据将丢失,并且垃圾回收功能将回收此文件。 这些文件适用于为进程间通信 (IPC) 创建共享内存。

内存映射文件可以在多个进程之间进行共享。 进程可以通过使用由创建同一内存映射文件的进程所指派的公用名来映射到此文件。

若要使用一个内存映射文件,则必须创建该内存映射文件的完整视图或部分视图。 还可以创建内存映射文件的同一部分的多个视图,进而创建并发内存。 为了使两个视图能够并发,必须基于同一内存映射文件创建这两个视图。

如果文件大于应用程序用于内存映射的逻辑内存空间(在 32 位计算机上为 2 GB),则还需要使用多个视图。

有两种类型的视图:流访问视图和随机访问视图。 使用流访问视图可对文件进行顺序访问;对于非持久文件和 IPC,这是建议的方法。 在使用持久文件时,随机访问视图是首选方法。

由于内存映射文件是通过操作系统的内存管理器访问的,因此会自动将此文件分隔为多个页,并根据需要对其进行访问。 您不需要自行处理内存管理。

下图演示多个进程如何同时具有对同一内存映射文件的多个重叠视图。

内存映射文件的多个重叠视图

下表提供有关使用内存映射文件对象及其成员的指南。

 

任务

使用的方法或属性

MemoryMappedFile object that represents a persisted memory-mapped file from a file on disk.‘ data-guid="84b3db52f3f2718b5257afe65060e898"> 从磁盘上的文件中获取表示持久内存映射文件的 MemoryMappedFile 对象。

MemoryMappedFile.CreateFromFile method.‘ data-guid="c29cef5cde3162298b9bc85667764173">MemoryMappedFile.CreateFromFile 方法。

MemoryMappedFile object that represents a non-persisted memory-mapped file (not associated with a file on disk).‘ data-guid="d2b6c25bccb8d94ebb82cf72d24d922e"> 获取表示非持久内存映射文件(与磁盘上的文件不关联)的 MemoryMappedFile 对象。

MemoryMappedFile.CreateNew method.‘ data-guid="4d950d0d7be269266cadc4691c5a77de">MemoryMappedFile.CreateNew 方法。

- 或 -

MemoryMappedFile.CreateOrOpen method.‘ data-guid="a02507c676095b137903b4d139c4506c">MemoryMappedFile.CreateOrOpen 方法。

MemoryMappedFile object of an existing memory-mapped file (either persisted or non-persisted).‘ data-guid="2eb29815b9d38d5575c762a34a2f6a7f"> 获取现有内存映射文件(持久文件或非持久文件)的 MemoryMappedFile 对象。

MemoryMappedFile.OpenExisting method.‘ data-guid="931b496a3516abff5a06e4f9e269a1a5">MemoryMappedFile.OpenExisting 方法。

UnmanagedMemoryStream object for a sequentially accessed view to the memory-mapped file.‘ data-guid="e6d1a01155453800829dbcac5493b88b"> 获取针对内存映射文件的顺序访问视图的 UnmanagedMemoryStream 对象。

MemoryMappedFile.CreateViewStream method.‘ data-guid="1d3fbcb428a5c648bdf4f16d4d3cc613">MemoryMappedFile.CreateViewStream 方法。

UnmanagedMemoryAccessor object for a random access view to a memory-mapped fie.‘ data-guid="bc5e422f233e21a4d68a25b5185d6226"> 获取针对内存映射文件的随机访问视图的 UnmanagedMemoryAccessor 对象。

MemoryMappedFile.CreateViewAccessor method.‘ data-guid="7a92708ab63f5deb6c41570ca6dfa2a4">MemoryMappedFile.CreateViewAccessor 方法。

SafeMemoryMappedViewHandle object to use with unmanaged code.‘ data-guid="8bc20664cbd1732e32b9284bab643fcf"> 获取要用于非托管代码的 SafeMemoryMappedViewHandle 对象。

MemoryMappedFile.SafeMemoryMappedFileHandle property.‘ data-guid="aa48be535feea0f1c26f9ad840d23cfa">MemoryMappedFile.SafeMemoryMappedFileHandle 属性。

- 或 -

MemoryMappedViewAccessor.SafeMemoryMappedViewHandle property.‘ data-guid="0d9517f4847f85cdfc97594425994470">MemoryMappedViewAccessor.SafeMemoryMappedViewHandle 属性。

- 或 -

MemoryMappedViewStream.SafeMemoryMappedViewHandle property.‘ data-guid="b6389c0f21fa90a63b6dd981d00835ba">MemoryMappedViewStream.SafeMemoryMappedViewHandle 属性。

将内存分配推迟到创建视图后进行(仅限于非持久文件)。

Environment.SystemPageSize property.)‘ data-guid="f70f2d52bf77e1bb30c5a27edec52e72"> (若要确定当前系统页大小,请使用 Environment.SystemPageSize 属性。)

CreateNew method with the MemoryMappedFileOptions.DelayAllocatePages value.‘ data-guid="51b06d0f3636a0ae47db32bc7294c666"> 带 MemoryMappedFileOptions.DelayAllocatePages 值的 CreateNew 方法。

- 或 -

CreateOrOpen methods that have a MemoryMappedFileOptions enumeration as a parameter. ‘ data-guid="a67a1d9f4871a307eedc7b96a48f5a36">将 MemoryMappedFileOptions 枚举作为参数的 CreateOrOpen 方法。

安全性

MemoryMappedFileAccess enumeration as a parameter: ‘ data-guid="86fefe15251b7372d5cf8d17157ac133"> 在创建内存映射文件时,可以通过使用以下方法(这些方法采用 MemoryMappedFileAccess 枚举作为参数)来应用访问权限:

OpenExisting methods that take an MemoryMappedFileRights as a parameter.‘ data-guid="3c8d6dd7e33fc76c6a55d19bfeccc48e">通过使用将 MemoryMappedFileRights 用作参数的 OpenExisting 方法,可以指定用于打开现有内存映射文件的访问权限。

MemoryMappedFileSecurity object that contains predefined access rules. ‘ data-guid="e8014fd1838a10a77b1bab8398582228"> 此外,可以包含一个 MemoryMappedFileSecurity 对象,该对象包括预定义的访问规则。

SetAccessControl method.‘ data-guid="202f7161cd8474655a4989af4853ceb2"> 若要将新的或已更改的访问规则应用于内存映射文件,请使用 SetAccessControl 方法。 GetAccessControl method.‘ data-guid="e5fc88505d650e0d3ce9b54740352809">若要从现有文件中检索访问规则或审核规则,请使用 GetAccessControl 方法。

持久内存映射文件

CreateFromFile methods create a memory-mapped file from an existing file on disk.‘ data-guid="71ef62f93b7b9031ebb7f21e996fcfea">CreateFromFile 方法基于磁盘上的现有文件创建一个内存映射文件。

下面的示例创建一个特大文件的某一部分的内存映射视图,并操作该文件的某一部分。

 
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;

class Program
{
    static void Main(string[] args)
    {
        long offset = 0x10000000; // 256 megabytes
        long length = 0x20000000; // 512 megabytes

        // Create the memory-mapped file.
        using (var mmf = MemoryMappedFile.CreateFromFile(@"c:\ExtremelyLargeImage.data", FileMode.Open,"ImgA"))
        {
            // Create a random access view, from the 256th megabyte (the offset)
            // to the 768th megabyte (the offset plus length).
            using (var accessor = mmf.CreateViewAccessor(offset, length))
            {
                int colorSize = Marshal.SizeOf(typeof(MyColor));
                MyColor color;

                // Make changes to the view.
                for (long i = 0; i < length; i += colorSize)
                {
                    accessor.Read(i, out color);
                    color.Brighten(10);
                    accessor.Write(i, ref color);
                }
            }

        }
    }
}

public struct MyColor
{
    public short Red;
    public short Green;
    public short Blue;
    public short Alpha;

    // Make the view brighter.
    public void Brighten(short value)
    {
        Red = (short)Math.Min(short.MaxValue, (int)Red + value);
        Green = (short)Math.Min(short.MaxValue, (int)Green + value);
        Blue = (short)Math.Min(short.MaxValue, (int)Blue + value);
        Alpha = (short)Math.Min(short.MaxValue, (int)Alpha + value);
    }
}


下面的示例为另一个进程打开同一内存映射文件。

 
using System;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;


class Program
{
    static void Main(string[] args)
    {
        // Assumes another process has created the memory-mapped file.
        using (var mmf = MemoryMappedFile.OpenExisting("ImgA"))
        {
            using (var accessor = mmf.CreateViewAccessor(4000000, 2000000))
            {
                int colorSize = Marshal.SizeOf(typeof(MyColor));
                MyColor color;

                // Make changes to the view.
                for (long i = 0; i < 1500000; i += colorSize)
                {
                    accessor.Read(i, out color);
                    color.Brighten(20);
                    accessor.Write(i, ref color);
                }
            }
        }
    }
}

public struct MyColor
{
    public short Red;
    public short Green;
    public short Blue;
    public short Alpha;

    // Make the view brigher.
    public void Brighten(short value)
    {
        Red = (short)Math.Min(short.MaxValue, (int)Red + value);
        Green = (short)Math.Min(short.MaxValue, (int)Green + value);
        Blue = (short)Math.Min(short.MaxValue, (int)Blue + value);
        Alpha = (short)Math.Min(short.MaxValue, (int)Alpha + value);
    }
}


非持久内存映射文件

CreateNew and CreateOrOpen methods create a memory-mapped file that is not mapped to an existing file on disk.‘ data-guid="2b33f15ed02d21bbf1a517a197370a94"> CreateNew CreateOrOpen 方法创建一个未映射到磁盘上的现有文件的内存映射文件。

下面的示例由三个单独的进程(控制台应用程序)组成,这些进程将布尔值写入到内存映射文件中。 将发生下面一系列操作:

  1. Process A creates the memory-mapped file and writes a value to it. ‘ data-guid="897252268eae4cd88b08d4c785e37b12"> Process A 创建内存映射文件并将一个值写入到其中。

  2. Process B opens the memory-mapped file and writes a value to it. ‘ data-guid="2bf5364640a4c097b0fc50038a9a4f5c"> Process B 打开内存映射文件并将一个值写入到其中。

  3. Process C opens the memory-mapped file and writes a value to it. ‘ data-guid="a69df326ca5ad3c18ad5856dec9c2be2"> Process C 打开内存映射文件并将一个值写入到其中。

  4. Process A reads and displays the values from the memory-mapped file. ‘ data-guid="1f1e14e9b50623a8c13935a37868e97b"> Process A 读取并显示内存映射文件中的值。

  5. Process A is finished with the memory-mapped file, the file is immediately reclaimed by garbage collection.‘ data-guid="821b6c23f8c1aac92df01fd94b120777"> Process A 使用完内存映射文件后,垃圾回收功能将会立即回收该文件。

若要运行此示例,请执行以下步骤:

  1. 编译应用程序并打开三个命令提示符窗口。

  2. Process A.‘ data-guid="3b9b56f7afcc56f3a870dff6ee8ea280"> 在第一个命令提示符窗口中,运行 Process A

  3. Process B.‘ data-guid="2f1105a87495129dfaef663dd6b60426"> 在第二个命令提示符窗口中,运行 Process B

  4. Process A and press ENTER.‘ data-guid="fc75b5d20d0b18184557e22e2d812115"> 返回到 Process A 并按 Enter。

  5. Process C.‘ data-guid="3b1d8fdd0ed4d91b963f0a398492944c"> 在第三个命令提示符窗口中,运行 Process C

  6. Process A and press ENTER.‘ data-guid="fc75b5d20d0b18184557e22e2d812115"> 返回到 Process A 并按 Enter。

Process A is as follows:‘ data-guid="afb37d402e4c86f87459113712221730"> Process A 的输出如下所示:

 
 
Start Process B and press ENTER to continue.
Start Process C and press ENTER to continue.
Process A says: True
Process B says: False
Process C says: True

进程 A

 
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;

class Program
{
    // Process A:
    static void Main(string[] args)
    {
        using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 10000))
        {
            bool mutexCreated;
            Mutex mutex = new Mutex(true, "testmapmutex", out mutexCreated);
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(1);
            }
            mutex.ReleaseMutex();

            Console.WriteLine("Start Process B and press ENTER to continue.");
            Console.ReadLine();

            Console.WriteLine("Start Process C and press ENTER to continue.");
            Console.ReadLine();

            mutex.WaitOne();
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("Process A says: {0}", reader.ReadBoolean());
                Console.WriteLine("Process B says: {0}", reader.ReadBoolean());
                Console.WriteLine("Process C says: {0}", reader.ReadBoolean());
            }
            mutex.ReleaseMutex();
        }
    }
}


进程 B

 
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;

class Program
{
    // Process B:
    static void Main(string[] args)
    {
        try
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap"))
            {

                Mutex mutex = Mutex.OpenExisting("testmapmutex");
                mutex.WaitOne();

                using (MemoryMappedViewStream stream = mmf.CreateViewStream(1, 0))
                {
                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write(0);
                }
                mutex.ReleaseMutex();
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Memory-mapped file does not exist. Run Process A first.");
        }
    }
}


进程 C

 
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;

class Program
{
    // Process C:
    static void Main(string[] args)
    {
        try
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap"))
            {

                Mutex mutex = Mutex.OpenExisting("testmapmutex");
                mutex.WaitOne();

                using (MemoryMappedViewStream stream = mmf.CreateViewStream(2, 0))
                {
                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write(1);
                }
                mutex.ReleaseMutex();
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Memory-mapped file does not exist. Run Process A first, then B.");
        }
    }
}


MemoryMappedFile 内存映射文件 msdn,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。