0

我需要尽快将字典存储到文件中。键和值都是对象,不保证被标记为可序列化。此外,我更喜欢一种比序列化数千个对象更快的方法。因此,我研究了 .NET 4 中的映射内存文件支持。但是,MemoryMappedViewAccessor 似乎只允许存储结构而不是引用类型。

有没有办法存储文件的引用类型使用的内存并从该内存块重建对象(没有二进制序列化)?

4

3 回答 3

1

内存映射文件从根本上与垃圾收集器不兼容。这就是为什么.NET 支持这样一个主要的操作系统功能需要很长时间的原因。引用类型需要序列化到 MMF 视图 MemoryMappedViewStream,没有办法。类似的限制存在于非托管代码中,带有指针的对象需要被展平,这样指向的对象在视图中也是可见的。

无论您将它们序列化为 MMF 还是文件都不会有任何区别,文件系统缓存也是使用 MMF 实现的。只要写入的数据适合可用的可映射内存,文件写入非常快。如果这是一个问题,那么请查看 64 位操作系统来解决该问题。

于 2010-04-27T17:29:32.667 回答
1

I believe that storing a blob of memory is simply unworkable because that memory, if it has reference types, will have pointers to other blocks of memory that will likely not apply next time the file is accessed. That's why binary serialization exists: to maintain these kinds of references. If you really want tight control, though, I would use System.IO.BinaryWriter and BinaryReader to have full control over exactly what is written to the file in what sequence, while minimizing overhead.

于 2010-04-27T16:35:41.900 回答
0

This is the type of scenario that binary serialization was designed for. Is there some specific reason why you don't want to use that? Have you verified that it's 'too slow'? Sure, you can code your own custom serializer and probably make it more efficient for your specific scenario, but then you'll have to maintain it going forward. Is it worth the effort?

于 2010-04-27T16:32:02.417 回答