gpt4 book ai didi

c# - 如何在 C# 中清空/刷新 Windows READ 磁盘缓存?

转载 作者:太空狗 更新时间:2023-10-29 19:49:33 24 4
gpt4 key购买 nike

如果我试图确定驱动器的读取速度,我可以编写一个例程来将文件写入文件系统,然后再读回这些文件。不幸的是,这并不能提供准确的读取速度,因为 Windows 会进行磁盘读取缓存。

有没有办法在 C#/.Net 中刷新驱动器的磁盘读取缓存(或者可能使用 Win32 API 调用),以便我可以直接从驱动器读取文件而不缓存它们?

最佳答案

康斯坦丁:谢谢!该链接有一个命令行 EXE,可以执行我正在寻找的测试。

我还在该页面上找到了指向该页面上更有趣的文章(Word 和 PDF 格式)的链接:Sequential File Programming Patterns and Performance with .NET

在这篇文章中,它讨论了无缓冲文件性能(iow,没有读/写缓存——只有原始磁盘性能。)

文章直接引用:

There is no simple way to disable FileStream buffering in the V2 .NET framework. One must invoke the Windows file system directly to obtain an un-buffered file handle and then ‘wrap’ the result in a FileStream as follows in C#:

    [DllImport("kernel32", SetLastError=true)]
static extern unsafe SafeFileHandle CreateFile(
string FileName, // file name
uint DesiredAccess, // access mode
uint ShareMode, // share mode
IntPtr SecurityAttributes, // Security Attr
uint CreationDisposition, // how to create
uint FlagsAndAttributes, // file attributes
SafeFileHandle hTemplate // template file
);

SafeFileHandle handle = CreateFile(FileName,
FileAccess.Read,
FileShare.None,
IntPtr.Zero,
FileMode.Open,
FILE_FLAG_NO_BUFFERING,
null);

FileStream stream = new FileStream(handle,
FileAccess.Read,
true,
4096);

Calling CreateFile() with the FILE_FLAG_NO_BUFFERING flag tells the file system to bypass all software memory caching for the file. The ‘true’ value passed as the third argument to the FileStream constructor indicates that the stream should take ownership of the file handle, meaning that the file handle will automatically be closed when the stream is closed. After this hocus-pocus, the un-buffered file stream is read and written in the same way as any other.

关于c# - 如何在 C# 中清空/刷新 Windows READ 磁盘缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/122362/

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