gpt4 book ai didi

c# - FileStream.WriteFile 的奇怪行为

转载 作者:太空狗 更新时间:2023-10-29 17:58:39 29 4
gpt4 key购买 nike

我正在开发一个对大文件(直到 64 GB)进行大量读/写随机访问的程序。文件是专门结构化的,为了访问它们,我创建了一个框架;过了一会儿,我尝试测试它的性能,我注意到在预分配文件上,顺序写入操作太慢了,无法接受。经过多次测试后,我在没有框架的情况下复制了行为(仅 FileStream 方法);这是(使用我的硬件)复制问题的代码部分:

FileStream fs = new FileStream("test1.vhd", FileMode.Open);
byte[] buffer = new byte[256 * 1024];
Random rand = new Random();
rand.NextBytes(buffer);
DateTime start, end;
double ellapsed = 0.0;
long startPos, endPos;

BinaryReader br = new BinaryReader(fs);
br.ReadUInt32();
br.ReadUInt32();
for (int i = 0; i < 65536; i++)
br.ReadUInt16();

br = null;

startPos = 0; // 0
endPos = 4294967296; // 4GB
for (long index = startPos; index < endPos; index += buffer.Length)
{
start = DateTime.Now;
fs.Write(buffer, 0, buffer.Length);
end = DateTime.Now;
ellapsed += (end - start).TotalMilliseconds;
}

不幸的是,这个问题似乎是不可预测的,所以有时它“有效”,有时却无效。但是,使用 Process Monitor 我发现了以下事件:

Operation   Result  DetailWriteFile   SUCCESS Offset: 1.905.655.816, Length: 262.144WriteFile   SUCCESS Offset: 1.905.917.960, Length: 262.144WriteFile   SUCCESS Offset: 1.906.180.104, Length: 262.144WriteFile   SUCCESS Offset: 1.906.442.248, Length: 262.144WriteFile   SUCCESS Offset: 1.906.704.392, Length: 262.144WriteFile   SUCCESS Offset: 1.906.966.536, Length: 262.144ReadFile    SUCCESS Offset: 1.907.228.672, Length: 32.768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O, Priority: NormalWriteFile   SUCCESS Offset: 1.907.228.680, Length: 262.144ReadFile    SUCCESS Offset: 1.907.355.648, Length: 32.768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O, Priority: NormalReadFile    SUCCESS Offset: 1.907.490.816, Length: 32.768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O, Priority: NormalWriteFile   SUCCESS Offset: 1.907.490.824, Length: 262.144ReadFile    SUCCESS Offset: 1.907.617.792, Length: 32.768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O, Priority: NormalReadFile    SUCCESS Offset: 1.907.752.960, Length: 32.768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O, Priority: NormalWriteFile   SUCCESS Offset: 1.907.752.968, Length: 262.144

也就是说,在覆盖了将近 2 GB 之后,FileStream.Write 开始在每次 WriteFile 之后调用 ReadFile,并且这个问题继续直到过程结束;此外,问题开始的偏移量似乎是随机的。我已经在 FileStream.Write 方法中逐步调试,并且我已经验证实际上是 WriteFile (Win32 API) 在内部调用 读取文件

最后一个音符;我不认为这是一个文件碎片问题:我已经用 contig 亲自对文件进行了碎片整理!

最佳答案

我认为这与 FileStream.Write/Read 和 2GB 限制有关。你是在 32 位进程中运行它吗?我找不到关于此的任何特定文档,但这里有一个 MSDN forum听起来一样的问题。您可以尝试在 64 位进程中运行它。

不过我同意使用内存映射文件可能是更好的方法。

关于c# - FileStream.WriteFile 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4875075/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com