15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Mapped-Memory files ❘ 799<br />

figure 29-12<br />

maPPed-memory files<br />

If you have been working your entire coding life with only managed code, then mapped-memory files might<br />

be a br<strong>and</strong> new concept. .<strong>NET</strong> Framework 4 now supplies mapped-memory files as part of your toolkit for<br />

building applications with the introduction of the System.IO.MemoryMappedFiles namespace.<br />

It is always possible to use the concept of mapped-memory files by doing some P/Invokes to the underlying<br />

Windows APIs, but now with the introduction of the System.IO.MemoryMappedFiles namespace, you can<br />

work with managed code rather than operating in the cumbersome P/Invoke world.<br />

Mapped-memory files <strong>and</strong> the use of this namespace are ideal when your application requires frequent or<br />

r<strong>and</strong>om access to files. Using this approach allows you to load part or all of the file into a segment of virtual<br />

memory, which then appears to your application as if this file is contained within the primary memory for<br />

the application.<br />

Interestingly, you can use this file in memory as a shared resource among more than one process. Prior<br />

to this, you might have been using Windows Communication Foundation (WCF) or Named Pipes to<br />

communicate a shared resource between multiple processes, but now you can share a mapped-memory file<br />

between processes using a shared name.<br />

To work with mapped-memory files, you have to work with a couple of objects. The first is a<br />

mapped-memory file instance that loads the file. The second is an accessor object. The following code<br />

writes to the mapped-memory file object <strong>and</strong> then reads from it. You also see that the write is also<br />

happening when the object is disposed:<br />

using System;<br />

using System.IO.MemoryMappedFiles;<br />

using System.Text;<br />

namespace MappedMemoryFiles<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!