MemoryMappedFile Класс
Определение
Представляет размещенный в памяти файл.Represents a memory-mapped file.
public ref class MemoryMappedFile : IDisposable
public class MemoryMappedFile : IDisposable
type MemoryMappedFile = class
interface IDisposable
Public Class MemoryMappedFile
Implements IDisposable
- Наследование
-
MemoryMappedFile
- Реализации
Примеры
В следующем примере создается отображенное в память представление для части очень большого файла, с которым выполняются определенные действия:The following example creates a memory-mapped view of a part of an extremely large file and manipulates a portion of it.
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
long offset = 0x10000000; // 256 megabytes
long length = 0x20000000; // 512 megabytes
// Create the memory-mapped file.
using (var mmf = MemoryMappedFile.CreateFromFile(@"c:\ExtremelyLargeImage.data", FileMode.Open,"ImgA"))
{
// Create a random access view, from the 256th megabyte (the offset)
// to the 768th megabyte (the offset plus length).
using (var accessor = mmf.CreateViewAccessor(offset, length))
{
int colorSize = Marshal.SizeOf(typeof(MyColor));
MyColor color;
// Make changes to the view.
for (long i = 0; i < length; i += colorSize)
{
accessor.Read(i, out color);
color.Brighten(10);
accessor.Write(i, ref color);
}
}
}
}
}
public struct MyColor
{
public short Red;
public short Green;
public short Blue;
public short Alpha;
// Make the view brighter.
public void Brighten(short value)
{
Red = (short)Math.Min(short.MaxValue, (int)Red + value);
Green = (short)Math.Min(short.MaxValue, (int)Green + value);
Blue = (short)Math.Min(short.MaxValue, (int)Blue + value);
Alpha = (short)Math.Min(short.MaxValue, (int)Alpha + value);
}
}
Imports System.IO
Imports System.IO.MemoryMappedFiles
Imports System.Runtime.InteropServices
Class Program
Sub Main()
Dim offset As Long = &H10000000 ' 256 megabytes
Dim length As Long = &H20000000 ' 512 megabytes
' Create the memory-mapped file.
Using mmf = MemoryMappedFile.CreateFromFile("c:\ExtremelyLargeImage.data", FileMode.Open, "ImgA")
' Create a random access view, from the 256th megabyte (the offset)
' to the 768th megabyte (the offset plus length).
Using accessor = mmf.CreateViewAccessor(offset, length)
Dim colorSize As Integer = Marshal.SizeOf(GetType(MyColor))
Dim color As MyColor
Dim i As Long = 0
' Make changes to the view.
Do While (i < length)
accessor.Read(i, color)
color.Brighten(10)
accessor.Write(i, color)
i += colorSize
Loop
End Using
End Using
End Sub
End Class
Public Structure MyColor
Public Red As Short
Public Green As Short
Public Blue As Short
Public Alpha As Short
' Make the view brighter.
Public Sub Brighten(ByVal value As Short)
Red = CType(Math.Min(Short.MaxValue, (CType(Red, Integer) + value)), Short)
Green = CType(Math.Min(Short.MaxValue, (CType(Green, Integer) + value)), Short)
Blue = CType(Math.Min(Short.MaxValue, (CType(Blue, Integer) + value)), Short)
Alpha = CType(Math.Min(Short.MaxValue, (CType(Alpha, Integer) + value)), Short)
End Sub
End Structure
Комментарии
Размещенный в памяти файл сопоставляет содержимое файла с логическим адресным пространством приложения.A memory-mapped file maps the contents of a file to an application's logical address space. Размещенные в памяти файлы позволяют программистам работать с очень большими файлами, так как память может управляться параллельно, и они обеспечивают полный, произвольный доступ к файлу без необходимости поиска.Memory-mapped files enable programmers to work with extremely large files because memory can be managed concurrently, and they allow complete, random access to a file without the need for seeking. Размещенные в памяти файлы также могут совместно использоваться несколькими процессами.Memory-mapped files can also be shared across multiple processes.
Методы создают размещенный в памяти файл по указанному пути FileStream или к существующему файлу на диске. CreateFromFileThe CreateFromFile methods create a memory-mapped file from a specified path or a FileStream of an existing file on disk. Изменения автоматически распространяются на диск при несопоставленном файле.Changes are automatically propagated to disk when the file is unmapped.
CreateNew Методы создают размещенный в памяти файл, который не сопоставляется с существующим файлом на диске; и подходит для создания общей памяти для межпроцессного взаимодействия (IPC).The CreateNew methods create a memory-mapped file that is not mapped to an existing file on disk; and are suitable for creating shared memory for interprocess communication (IPC).
Размещенный в памяти файл может быть связан с необязательным именем, который позволяет совместно использовать размещенный в памяти файл с другими процессами.A memory-mapped file can be associated with an optional name that allows the memory-mapped file to be shared with other processes.
Можно создать несколько представлений сопоставленного в память файла, включая представления частей файла.You can create multiple views of the memory-mapped file, including views of parts of the file. Одну и ту же часть файла можно связать с более чем одним адресом для создания параллельной памяти.You can map the same part of a file to more than one address to create concurrent memory. Чтобы два представления оставались согласованными, их нужно создавать из одного отображенного в память файла.For two views to remain concurrent, they have to be created from the same memory-mapped file. Создание двух сопоставлений файлов одного и того же файла с двумя представлениями не обеспечивает параллелизм.Creating two file mappings of the same file with two views does not provide concurrency.
Свойства
SafeMemoryMappedFileHandle |
Получает дескриптор размещенного в памяти файла.Gets the file handle of a memory-mapped file. |
Методы
CreateFromFile(FileStream, String, Int64, MemoryMappedFileAccess, HandleInheritability, Boolean) |
Создает из существующего файла отображенный в память файл с заданными режимом доступа, именем, режимом наследования и емкостью.Creates a memory-mapped file from an existing file with the specified access mode, name, inheritability, and capacity. |
CreateFromFile(FileStream, String, Int64, MemoryMappedFileAccess, MemoryMappedFileSecurity, HandleInheritability, Boolean) |
Создает из файла на диске размещенный в памяти файл с указанными именем, емкостью, типом доступа, разрешениями безопасности, режимом наследования и требованием к ликвидации.Creates a memory-mapped file that has the specified name, capacity, access type, security permissions, inheritability, and disposal requirement from a file on disk. |
CreateFromFile(String) |
Создает размещенный в памяти файл из файла на диске.Creates a memory-mapped file from a file on disk. |
CreateFromFile(String, FileMode) |
Создает из файла на диске размещенный в памяти файл с заданным режимом доступа.Creates a memory-mapped file that has the specified access mode from a file on disk. |
CreateFromFile(String, FileMode, String) |
Создает из файла на диске размещенный в памяти файл с заданным режимом доступа и именем.Creates a memory-mapped file that has the specified access mode and name from a file on disk. |
CreateFromFile(String, FileMode, String, Int64) |
Создает из файла на диске размещенный в памяти файл с заданным режимом доступа, именем и емкостью.Creates a memory-mapped file that has the specified access mode, name, and capacity from a file on disk. |
CreateFromFile(String, FileMode, String, Int64, MemoryMappedFileAccess) |
Создает из файла на диске размещенный в памяти файл с указанными режимом доступа, именем, емкостью и типом доступа.Creates a memory-mapped file that has the specified access mode, name, capacity, and access type from a file on disk. |
CreateNew(String, Int64) |
Создает размещенный в памяти файл с заданной емкостью в системной памяти.Creates a memory-mapped file that has the specified capacity in system memory. |
CreateNew(String, Int64, MemoryMappedFileAccess) |
Создает размещенный в памяти файл с заданной емкостью и типом доступа в системной памяти.Creates a memory-mapped file that has the specified capacity and access type in system memory. |
CreateNew(String, Int64, MemoryMappedFileAccess, MemoryMappedFileOptions, HandleInheritability) |
Создает отображенный в память файл с заданными именем, емкостью, типом доступа, параметрами выделения памяти и режимом наследования.Creates a memory-mapped file that has the specified name, capacity, access type, memory allocation options and inheritability. |
CreateNew(String, Int64, MemoryMappedFileAccess, MemoryMappedFileOptions, MemoryMappedFileSecurity, HandleInheritability) |
Создает размещенный в памяти файл с заданной емкостью, типом доступа, выделением памяти, настройками безопасности и режимом наследования в системной памяти.Creates a memory-mapped file that has the specified capacity, access type, memory allocation, security permissions, and inheritability in system memory. |
CreateOrOpen(String, Int64) |
Создает или открывает отображенный в память файл с заданным именем и емкостью в системной памяти.Creates or opens a memory-mapped file that has the specified name and capacity in system memory. |
CreateOrOpen(String, Int64, MemoryMappedFileAccess) |
Создает или открывает отображенный в память файл с заданным именем, емкостью и типом доступа в системной памяти.Creates or opens a memory-mapped file that has the specified name, capacity and access type in system memory. |
CreateOrOpen(String, Int64, MemoryMappedFileAccess, MemoryMappedFileOptions, HandleInheritability) |
Создает пустой отображенный в память файл или открывает существующий отображенный в память файл, если он уже существует с таким же именем.Creates a new empty memory mapped file or opens an existing memory mapped file if one exists with the same name. При открытии существующего файла емкость, параметры и аргументы памяти игнорируются.If opening an existing file, the capacity, options, and memory arguments will be ignored. |
CreateOrOpen(String, Int64, MemoryMappedFileAccess, MemoryMappedFileOptions, MemoryMappedFileSecurity, HandleInheritability) |
Создает или открывает отображенный в память файл с заданным именем, емкостью, типом доступа, выделением памяти, разрешениями безопасности и режимом наследования в системной памяти.Creates or opens a memory-mapped file that has the specified name, capacity, access type, memory allocation, security permissions, and inheritability in system memory. |
CreateViewAccessor() |
Создает метод MemoryMappedViewAccessor, который соответствует представлению размещенного в памяти файла.Creates a MemoryMappedViewAccessor that maps to a view of the memory-mapped file. |
CreateViewAccessor(Int64, Int64) |
Создает MemoryMappedViewAccessor, который сопоставляется с представлением размещенного в памяти файла и имеет заданное смещение и размер.Creates a MemoryMappedViewAccessor that maps to a view of the memory-mapped file, and that has the specified offset and size. |
CreateViewAccessor(Int64, Int64, MemoryMappedFileAccess) |
Создает MemoryMappedViewAccessor, который сопоставляется с представлением размещенного в памяти файла и имеет заданное смещение, размер и ограничения по доступу.Creates a MemoryMappedViewAccessor that maps to a view of the memory-mapped file, and that has the specified offset, size, and access restrictions. |
CreateViewStream() |
Создает поток, который соответствует представлению размещенного в памяти файла.Creates a stream that maps to a view of the memory-mapped file. |
CreateViewStream(Int64, Int64) |
Создает поток, который сопоставляется с представлением размещенного в памяти файла и имеет заданное смещение и размер.Creates a stream that maps to a view of the memory-mapped file, and that has the specified offset and size. |
CreateViewStream(Int64, Int64, MemoryMappedFileAccess) |
Создает поток, который сопоставляется с представлением размещенного в памяти файла и имеет заданное смещение, размер и тип доступа.Creates a stream that maps to a view of the memory-mapped file, and that has the specified offset, size, and access type. |
Dispose() |
Освобождает все ресурсы, используемые объектом MemoryMappedFile.Releases all resources used by the MemoryMappedFile. |
Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые объектом MemoryMappedFile, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by the MemoryMappedFile and optionally releases the managed resources. |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GetAccessControl() |
Получает элемент управления доступом к ресурсу размещенного в памяти файла.Gets the access control to the memory-mapped file resource. |
GetHashCode() |
Служит в качестве хэш-функции по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
OpenExisting(String) |
Открывает существующий размещенный в памяти файл с заданным именем в системной памяти.Opens an existing memory-mapped file that has the specified name in system memory. |
OpenExisting(String, MemoryMappedFileRights) |
Открывает существующий размещенный в памяти файл с заданными именем и правами доступа в системной памяти.Opens an existing memory-mapped file that has the specified name and access rights in system memory. |
OpenExisting(String, MemoryMappedFileRights, HandleInheritability) |
Открывает существующий размещенный в памяти файл с заданными именем, правами доступа и режимом наследования в системной памяти.Opens an existing memory-mapped file that has the specified name, access rights, and inheritability in system memory. |
SetAccessControl(MemoryMappedFileSecurity) |
Задает элемент управления доступом к ресурсу размещенного в памяти файла.Sets the access control to the memory-mapped file resource. |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |