可以访问从C#加载到另一个进程中的大型数据结构吗?

问题描述 投票:0回答:1

我有一个应用程序,该应用程序并行运行许多线程,每个线程处理相同的数百GB只读,从不以不同的方式更改数据。即使使用ZeroFormatter,在开始每次运行之前也需要花费一些时间将所有数据加载到内存中。我想消除这种等待。

在C#中,是否有可能一个进程将数据加载到内存中并持久保存,并在稍后启动另一个进程以有效地就地访问数据?

说明:这是时间序列数据,在具有0.5 TB内存的非常强大的硬件上按顺序处理。

c# parallel-processing shared-memory
1个回答
0
投票

看看memory mapped files。基本前提是,每个进程都“认为”它正在加载自己的文件,但实际上,它们都使用相同的物理视图。

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);
}
}
© www.soinside.com 2019 - 2024. All rights reserved.