Play memory ing file in. NET 4

Source: Internet
Author: User

Link: http://blogs.msdn.com/salvapatuel/archive/2009/06/08/working-with-memory-mapped-files-in-net-4.aspx

Prerequisites: This article requires you to have a certain understanding of OS Memory Management.

I would like to explore some distinctive new features in coming. NET 4, rather than the dynamic types, covariant and inverter features that have been well known by the public. Out of my preference for performance enhancement, I will post several blog posts on new features.

Memory ing files seem as unfamiliar to developers hosting the World (Voiceover: back to Mars, the Earth is very dangerous ). But it does have been around for years, and it is very important to say that it is in the operating system. In fact, any communication model that wants to share data will use it behind the scenes.

So what is the memory ing file? The memory ing file allows you to retain an address space and then submit it to the physical storage space (well, doesn't it sound like virtual memory ?). The main difference between the two is that physical storage comes from the existing files on the disk, rather than the Memory Manager. There are two main intentions to do this:

  • 1. to access data on disk files, you do not need to perform file I/O operations or cache file content. It is particularly useful when you access data in ultra-large files.
  • 2. You can use the memory ing file to share data between multiple processes running on the same machine.

The Windows operating system uses memory ing to execute DLL and load and execute EXE files.

The memory ing file is the most efficient way for data communication between multiple processes on a single machine. In addition, if you refer to other IPC methods, you will see the architecture shown in:

Woo ..., Now you are probably impressed with the power of this technology (in the namespace of System. IO, it can even completely replace the P/Invoke technology ).

Now, let me quickly explain how it works. We have two memory ing file models. One is to use a custom file. It can be any file that the application wants to access. The other is page files. We will share it with the Memory Manager (this is the most common technical model ).

First, we will introduce the User-Defined file model. The first thing we need to do is create a FileStream for the file we want to use. It can be an existing file or a new file (Remember, you should open this file in a shared manner, otherwise, other processes will not be able to access it ). After creating a suitable stream, you can now create a memory ing file. As follows:

1:  using System.IO.MemoryMappedFiles;
1:  MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(
2:                  new FileStream(@"E:\Temp\Map.mp", FileMode.Create), //Any stream will do it
3:                  "MyMemoryMappedFile",   //Name
4:                  1024 * 1024,    //Size in bytes
5:                  MemoryMappedFileAccess.ReadWrite);  //Access type

Here, I use a simple constructor of the MemoryMappedFile class. We defined the stream to be used and gave a name to the memory ing file. In addition, we also need to know the size (in bytes) and access type of the memory ing file. In this way, a memory ing file is created. However, before using it, we need a ing view. Next, we will create it:

MemoryMappedViewAccessor FileMapView = memoryMappedFile.CreateViewAccessor();

 

This ing overwrites the entire file. If we want to read or write information from the memory ing file now, just call the ing view method with the correct offset.

int number = 1234;
FileMapView.Write(0, number);
FileMapView.Write<Container>(4, ref container);

We can write data to any built-in type or custom type with generic constraints. A good feature of memory ing files is durability. Before you close it, the content will pile up on the disk. This is useful for sharing cache information between applications.

Well, how do other processes read the content of the memory ing file. Similarly, we first create a memory ing file. However, we use another constructor to open the existing memory ing file. If it does not exist, it is not too late to create a new one. The original code example is incorrect.

MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateOrOpen(
                "MyMemoryMappedFile",      
                1024 * 1024, 
                MemoryMappedFileAccess.ReadWrite);

Next, create a ing view to read the information, as shown below:

using (MemoryMappedViewAccessor FileMap = memoryMappedFile.CreateViewAccessor())
{
    Container newContainer = new Container();
    FileMap.Read<Container>(4, out newContainer);
}

Look, isn't it easy? However, this method has a small disadvantage, which is related to the size of the memory ing file. If you do not know the size beforehand, you may construct a super large file just in case. However, this wastes a lot of address space. After all, the address you reserve is much larger than the physical space you submit, isn't it?

To solve this problem, we can use the page file. This is very advantageous for submitting data in a busy schedule. But it also introduces a new problem: You don't have your own files, and the ing will continue until the last handle is destroyed. But think about it. This solution is quite reasonable.

Now let's reconstruct the previous example. This time, I will use the constructors with the most complete parameters to introduce some other features. Of course, these features also apply to custom files.

MemoryMappedFileSecurity customSecurity = new MemoryMappedFileSecurity();
MemoryMappedFile pagedMemoryMapped = MemoryMappedFile.CreateNew(
    @"Salvador",    //Name
    1024*1024,  //Size
    MemoryMappedFileAccess.ReadWrite,   //Access type
    MemoryMappedFileOptions.DelayAllocatePages, //Pseudo reserve/commit
    customSecurity, //You can customize the security
    HandleInheritability.Inheritable    //Inherit to child process
    );

The MemoryMappedFileSecurity class allows you to customize which process can access resources. This feature is useful when you want to protect sensitive information or do not want other processes to change the memory ing file. You can view all the settings of this object that you want to change. You can obtain more detailed information here. If we want to explore the structure of the memory ing file, we do not need to construct a stream. We only need to find the name of the resource. This links the ing name to the region based on the file size. So many processes know how to access files. Note: After the DelayAllocatePages attribute is used, the address space is reserved/submitted only when necessary. The last interesting parameter is the handle inheritance model. It allows sub-processes to share resources when necessary.

How to access a file is the same as the preceding example. Remember, if you close the memory ing file, it will be inaccessible. This problem has plagued many developers.

Finally, let's take a look at another interesting area: creating multiple ing views. They work simultaneously to access different regions of the same memory ing file. At this time, you must properly protect the content and synchronize access.

We can define different offsets and lengths to create our own ing views. As follows:

MemoryMappedViewAccessor writeMapView = memoryMappedFile.CreateViewAccessor(0, 1024,
    MemoryMappedFileAccess.ReadWrite);
MemoryMappedViewAccessor readMapView = memoryMappedFile.CreateViewAccessor(1025, 1024,
    MemoryMappedFileAccess.Read);

Now you can enjoy the power of the high-performance data sharing model brought about by. NET 4.0. Note: This article is based on. NET 4.0 BETA1.

Note: UNIX does not use ing files for Memory sharing. It has an explicit Memory Sharing API function. These function types are shmget, shmctl, shmat, shmdt, and mmap and munmap. Although the last two functions are a bit similar to those described in this article, they do not map objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.