C# 使用pinvoke的多线程ReadFile调用给出了无效的用户缓冲区状态
我正在编写一些代码,以绕过FileStream中的缓冲区从二进制文件读取块,因为使用LockFileEx锁定文件区域时会出现问题。这段代码与来自参考源的FileStream中的实现几乎相同C# 使用pinvoke的多线程ReadFile调用给出了无效的用户缓冲区状态,c#,multithreading,pinvoke,readfile,C#,Multithreading,Pinvoke,Readfile,我正在编写一些代码,以绕过FileStream中的缓冲区从二进制文件读取块,因为使用LockFileEx锁定文件区域时会出现问题。这段代码与来自参考源的FileStream中的实现几乎相同 private unsafe int ReadFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, out int hr) { int r = 0; int numBytesRead = 0; fi
private unsafe int ReadFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, out int hr)
{
int r = 0;
int numBytesRead = 0;
fixed (byte* p = bytes)
{
r = Native.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
}
将ReadFile导入到以下位置:
unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes,
int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
我的代码有8个线程,每个线程都试图从文件中读取,每个线程都有一个单独的文件句柄和自己的读取指针,我从一个80K块的35GB文件中读取。
偶尔,此读取失败并出现错误0xc00000e8(状态\无效\用户\缓冲区),但我不明白为什么
是什么导致了这个问题,我如何解决它?我使用GCHandle.Alloc解决了这个问题
GCHandle gch = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
r = WdfWin32Native.ReadFile(handle, bytes, count, out numBytesRead, IntPtr.Zero);
}
finally
{
gch.Free();
}
已声明ReadFile时:
unsafe internal static extern int ReadFile(SafeFileHandle handle,
byte [] bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
我不知道为什么这会解决这个问题,但它似乎确实解决了。pinvoke.net的下一页使用了readfile:我希望该代码偶尔会出现问题,因为它无法阻止垃圾收集器移动传递给readfile的缓冲区。代码看起来相当不错。您是否阅读了使用习惯用法?您正确地修改了ReadFile声明。因此,您也不再需要GCHandle,pinvoke marshaller已经锁定了阵列。