Using memory ing files in. Net 4.0 (2)

Source: Internet
Author: User

Previously, you have seen how to use a memory ing file to easily access the content of a file through some simple memory operations. The next step is to learn how to use this knowledge to share memory between your application and the program.
When ing the content of a file to the memory, you must specify the disk on which the file is stored and the part of the file you want to map. This is simple, but it is not obvious that you need to map the same file multiple times, even if the ing areas are the same or overlap (figure 2 ).

  

Figure 2. Each part of the file can be mapped multiple times.

With this knowledge, multiple threads can access the file content without worrying about concurrency and locking. This only knows how to read and write data from memory blocks. With the view accessor class, you already know how to do it. Here is an example of how to map from a file to more than one accessor object. Of course, your file name must match the new view accessor you created each time. If you use the same memory ing twice, this is easy to do:

...
Memorymappedviewaccessor accessor1 =

MMF. createviewaccessor ();

Memorymappedviewaccessor accessor2 =

MMF. createviewaccessor ();

// Write

Byte writechr = encoding. ASCII. getbytes ("Z") [0];

Accessor1.write (0, writechr );

// Read

Byte readchr = accessor2.readbyte (0 );

String status = (readchr = writechr )? "Match! ":" No match! ";

MessageBox. Show (Status); // match
Note that the file content changes once the memory block of the view is written. The operating system may not immediately refresh the changed data to the disk, but this is usually "near-instant ). There is no need for separate errors or refresh operations; this is one of the beauty of the memory ing file.

To share a ing file between programs, you must name your view. This name allows you to open a synchronization view in more than one program. Needless to say, this name must be unique among the object names in the system. Suppose you want to send a string from one program to another. Here is the code for opening a named Memory ing view and writing a simple string to the view:

Memorymappedfile MMF = memorymappedfile. createoropen (
"My-MMF-Map-name", 1000 );

Memorymappedviewaccessor accessor =

MMF. createviewaccessor ();

String message = "Hello, memory-mapped world! ";

Byte [] asciibytes = encoding. ASCII. getbytes (Message );

Accessor. writearray (0, asciibytes, 0, asciibytes. Length );

MessageBox. Show ("message written .");
 
Note that the above Code does not contain physical files containing data. For this reason, you need to specify a capacity parameter when calling the createoropen method. In the above Code, this is set to 1,000 bytes. This capacity defines the size of the memory block. Return to the example of sharing information between programs. The next step is to try to read the String Stack with the same name in other programs:

Memorymappedfile MMF = memorymappedfile. createoropen (
"My-MMF-Map-name", 1000 );

Memorymappedviewaccessor accessor =

MMF. createviewaccessor ();

Byte bytevalue;

Int Index = 0;

Stringbuilder message = new stringbuilder ();

Do

{

Bytevalue = accessor. readbyte (INDEX );

If (bytevalue! = 0)

{

Char asciichar = (char) bytevalue;

Message. append (asciichar );

}

Index ++;

} While (bytevalue! = 0 );

MessageBox. Show ("found text: \" "+ message + "\".");
In the above Code, the second program opens the same memory ing view by using the createoropen static method of the memorymappedfile class. Then, the accessor object is created as before, and one byte of data is read until the zero Terminator is found. The information is then processed and displayed on the screen. This is the easiest way to complete inter-process communication (IPC) between programs!

Create, extend, and intercept files

So far, you have learned how to access existing memory ing files on the disk, or create inter-process communications in real time. What should you do if you want to create a file from scratch, extend or intercept the file and map it To the memory? Fortunately, these three cases will be done straight away.

First, if you want to create a new file and create a memory ing view on it, you need to execute the following code:

Filestream file = new filestream (
@ "C: \ temp \ mynewfile. dat", filemode. createnew );

Memorymappedfile MMF =

Memorymappedfile. createfromfile (file, null, 1000 );

Memorymappedviewaccessor accessor =

MMF. createviewaccessor ();
 
Here, the new file is created by specifying the createnew method in the filestream constructor call. This will create a new, zero-length file on the disk. This empty file cannot be used directly to create a view. Therefore, the createfromfile method call must contain a capacity parameter. In the above example, the file has a capacity of 1,000 bytes. If nothing is written to the file, the file contains a zero value, that is, null.

Since the above file has a length of 1,000 bytes, how do you ignore the limitations and continue writing? If you map an attempt and use the accessor object write method to try to write the past file capacity (size), this operation will fail (may be different in future. net4.0 versions ). In this way, you cannot simply extend the file by writing the end of the previous file, you can use some streams.

Then how do you expand a file? The answer is that the capacity parameter of the createfromfile method is called in the memorymappedfile class. If you specify a larger capacity than the file on the disk, Windows will expand the file to match the given capacity. Obviously, this will succeed if the disk has enough space, so that even if you have enough memory, the capacity increase will not (always) continue to work.

The following code expands the size of a 1,000-byte file to 2,000 Bytes:

Filestream file = new filestream (
@ "C: \ temp \ mynewfile. dat", filemode. Open );

Memorymappedfile MMF =

Memorymappedfile. createfromfile (file, null, 2000 );
 
The capacity parameter is defined as a C #, meaning a 64-bit value (system. int64 ). You do not limit the size to 2 gigabyte bytes at a time, but you can use a larger view instead. In fact, the only restriction is the free virtual address space in your application, which is about 8 terabytes. If you have a 64-bit Windows operating system and compile your.. NET application becomes a 64-bit application (the x64 platform target mode in Visual Studio ). In general 32-bit systems, the limit is usually less than 2 GB, depending on system installation and memory usage. The third common operation, intercept, is different from the first two situations: the intercept of a file must be completed at the file layer. If you try to specify a capacity parameter value smaller than the actual file on the disk, you will get an error message that the capacity value cannot be smaller than the file size. Therefore. You must select another method. One of the methods is to use the setlength method of filestream.

To obtain the file size, you need to test the stream Length attribute or use the same name attribute of the system. Io. fileinfo class.

Summary

In this article, you learned about memory ing files and classes that support them in. NET Framework 4.0. Memory ing is a useful technique. Some simple memory operations allow a simple method to read and write files. You don't need any stream seeking, and you don't have to worry about the file being too large to adapt to the memory: Just map some of the files you need, you can do it.

Memory ing is useful not only for sharing data between threads of an application, but also for sharing data between programs running on the same system. To share data between programs, you need to give the mapped view object a unique name. If the name matches the name in other programs, the data will be automatically shared.

With. net4.0, you can use the management class to use memory ing files. Reading and writing data to the same ing view is completed through an accesssor object, or through a traditional stream. There are usually three steps to obtain the accessor object: First open the file using filestream, create a memory ing object, and finally obtain the accessor from the ing object.

Access objects allow you to easily read and write the most primitive data types, but General Data Types allow you to obtain more complex types, including arrays. A string can be read and written in one byte and one byte. You need to remember to make proper compilation for proper reading and writing.

Memory ing is a valuable technique for accessing File data, regardless of the file size. With. Net 4.0, Management Code developers should learn this new method and use it whenever they need it. It becomes the best alternative to more traditional methods for accessing files.

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.