1. 程式人生 > 實用技巧 >C# 記憶體對映研究學習

C# 記憶體對映研究學習

 class Program {
        static void Main(string[] args) {
            int size = 512;
            int position = 0;
            MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("1.mmf", FileMode.OpenOrCreate, "1", size);  //建立一個記憶體對映檔案
            MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor(0
, size); //建立一個檢視,提供操作途徑,操作的時候不經過IO,直接扔給底層系統 Console.WriteLine("硬碟檔案中的原始值===="); for (int i = 0; i < 12; i++) { //展示資料 Console.WriteLine(mmva.ReadByte(i)); } Console.WriteLine("開始嘗試操作=========="); mmva.Write(position, 255); //
寫一個位元組的資料255(byte) position++; //偏移位置,避免覆蓋其他的資料 mmva.Write(position, 0); position++; mmva.Write(position, 0); position++; int num = new Random().Next(int.MinValue, int.MaxValue); mmva.Write(position, num); //寫4個位元組的隨機(int)
position += 4; byte[] bs = new byte[] { 1, 2, 3, 4 }; //再寫4個固定的byte資料 mmva.WriteArray(position, bs, 0, bs.Length); for (int i = 0; i < 12; i++) { //展示資料 Console.WriteLine(mmva.ReadByte(i)); } Console.ReadKey(); } }

所謂記憶體對映就是建立一個指定大小的檔案,然後把這個檔案對映到記憶體中,然後使用操作的時候就能省去很多事,直接把資料扔給底層系統處理,這樣讀寫就會很快,用來儲存大量的資料就很爽,而且一個檔案貌似可以用多個檢視操作,所以這個技術可以作為不同程序之間的資料共享手段

class Program { static void Main(string[] args) { int size = 512; int position = 0; MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("1.mmf", FileMode.OpenOrCreate, "1", size); //建立一個記憶體對映檔案 MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor(0, size); //建立一個檢視,提供操作途徑,操作的時候不經過IO,直接扔給底層系統 Console.WriteLine("硬碟檔案中的原始值===="); for (int i = 0; i < 12; i++) { //展示0-9位元組的資料 Console.WriteLine(mmva.ReadByte(i)); } Console.WriteLine("開始嘗試操作=========="); mmva.Write(position, 255); //寫一個位元組的資料255(byte) position++; //偏移位置,避免覆蓋其他的資料 mmva.Write(position, 0); position++; mmva.Write(position, 0); position++; int num = new Random().Next(int.MinValue, int.MaxValue); mmva.Write(position, num); //寫4個位元組的隨機(int) position += 4; byte[] bs = new byte[] { 1, 2, 3, 4 }; //再寫4個固定的byte資料 mmva.WriteArray(position, bs, 0, bs.Length); for (int i = 0; i < 12; i++) { //展示0-9位元組的資料 Console.WriteLine(mmva.ReadByte(i)); } Console.ReadKey(); } }