最近一直為文件內存映射發愁,整個兩周一直折騰這個東西。在64位系統和32位系統還要針對內存的高低位進行計算。好麻煩。。還是沒搞定
偶然從MSDN上發現.NET 4.0把內存文件映射加到了.NET類庫中。。好像方便了很多啊。。比用C#直接調用WINDOWS API方便多了。所以
這個必須果斷記錄之。。。項目馬上要用,為了加強內存數據交換的效率。。這個。。。必須啊。。
|
|
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
持久文件內存映射:
CreateFromFile 方法基於磁盤上的現有文件創建一個內存映射文件。
2 using System.IO;
3 using System.IO.MemoryMappedFiles;
4 using System.Runtime.InteropServices;
5
6 class Program
7 {
8 static void Main( string[] args)
9 {
10 long offset = 0x10000000; // 256 megabytes
11 long length = 0x20000000; // 512 megabytes
12
13 // Create the memory-mapped file.
14 using ( var mmf = MemoryMappedFile.CreateFromFile( @" c:\ExtremelyLargeImage.data ", FileMode.Open, " ImgA "))
15 {
16 // Create a random access view, from the 256th megabyte (the offset)
17 // to the 768th megabyte (the offset plus length).
18 using ( var accessor = mmf.CreateViewAccessor(offset, length))
19 {
20 int colorSize = Marshal.SizeOf( typeof(MyColor));
21 MyColor color;
22
23 // Make changes to the view.
24 for ( long i = 0; i < length; i += colorSize)
25 {
26 accessor.Read(i, out color);
27 color.Brighten( 10);
28 accessor.Write(i, ref color);
29 }
30 }
31 }
32 }
33 }
34
35 public struct MyColor
36 {
37 public short Red;
38 public short Green;
39 public short Blue;
40 public short Alpha;
41
42 // Make the view brigher.
43 public void Brighten( short value)
44 {
45 Red = ( short)Math.Min( short.MaxValue, ( int)Red + value);
46 Green = ( short)Math.Min( short.MaxValue, ( int)Green + value);
47 Blue = ( short)Math.Min( short.MaxValue, ( int)Blue + value);
48 Alpha = ( short)Math.Min( short.MaxValue, ( int)Alpha + value);
49 }
50 }
非持久文件內存映射:
CreateNew 和 CreateOrOpen 方法創建一個未映射到磁盤上的現有文件的內存映射文件。
2 using System.IO;
3 using System.IO.MemoryMappedFiles;
4 using System.Threading;
5
6 class Program
7 {
8 // Process A:
9 static void Main( string[] args)
10 {
11 using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew( " testmap ", 10000))
12 {
13 bool mutexCreated;
14 Mutex mutex = new Mutex( true, " testmapmutex ", out mutexCreated);
15 using (MemoryMappedViewStream stream = mmf.CreateViewStream())
16 {
17 BinaryWriter writer = new BinaryWriter(stream);
18 writer.Write( 1);
19 }
20 mutex.ReleaseMutex();
21
22 Console.WriteLine( " Start Process B and press ENTER to continue. ");
23 Console.ReadLine();
24
25 Console.WriteLine( " Start Process C and press ENTER to continue. ");
26 Console.ReadLine();
27
28 mutex.WaitOne();
29 using (MemoryMappedViewStream stream = mmf.CreateViewStream())
30 {
31 BinaryReader reader = new BinaryReader(stream);
32 Console.WriteLine( " Process A says: {0} ", reader.ReadBoolean());
33 Console.WriteLine( " Process B says: {0} ", reader.ReadBoolean());
34 Console.WriteLine( " Process C says: {0} ", reader.ReadBoolean());
35 }
36 mutex.ReleaseMutex();
37 }
38 }
39 }