为什么FileStream.BeginRead不会结束 [英] Why FileStream.BeginRead doesn't end
问题描述
我正在编写一个读取USB读卡器的应用程序。我正在使用FileStream.BeginRead Async方法来读取usb CardReader。但它似乎没有回来。我想知道我在这里做错了什么? PC将读卡器视为键盘隐藏设备,我想知道这是不是问题。有人可以向我解释一下吗?
如果我把它拉出电脑,回拨功能才会返回
/// < 摘要 >
/// 初始化设备
/// < / summary >
/// < ; param name =strPath &g t; 设备的路径< / param >
私有 void 初始化( String strPath)
{
// 从设备路径创建文件
MySafeHandle = CreateFile(strPath,FileAccess.ReadWrite,FileShare.ReadWrite, IntPtr .Zero,FileMode.Open ,
EFileAttributes.Overlapped, IntPtr .Zero);
if (!MySafeHandle.IsInvalid) // 如果开放工作......
{
IntPtr lpData;
if (HidD_GetPreparsedData(MySafeHandle, out lpData))
// 获取窗口将设备数据读入内部缓冲区
{
尝试
{
HidCaps hidCaps;
HidP_GetCaps(lpData, out hidCaps); // 从内部缓冲区中提取设备功能
InputReportLength = hidCaps.InputReportByteLength; // 获取输入...
OutputReportLength = hidCaps.OutputReportByteLength; // ...和输出报告长度
MyFileStream = new FileStream((SafeFileHandle)MySafeHandle,FileAccess.ReadWrite,InputReportLength,
true ); // 将文件句柄包装在.Net文件流中
BeginAsyncRead(); // 启动第一次异步读取
}
finally
{
HidD_FreePreparsedData( ref lpData);
// 在我们退出功能之前,我们必须释放GetPreparsedData中保留的内部缓冲区
}
}
else // GetPreparsedData失败了吗?查找异常
throw HidDeviceException.GenerateWithWinError( GetPreparsedData failed);
}
其他 // 文件打开失败?查克异常
{
MySafeHandle.Dispose();
throw HidDeviceException.GenerateWithWinError( 失败创建设备文件);
}
}
这是BeginRead
< pre lang =c#> /// < 摘要 >
/ // 启动异步读取,该读取在读取数据或设备
/时完成// 已断开连接。使用回调。
/// < / summary >
private void BeginAsyncRead()
{
Byte [] buffer = new Byte [InputReportLength];
// 把我们用来接收东西的buff作为异步状态然后我们可以得到它读完成
IAsyncResult result = MyFileStream.BeginRead(buffer, 0 ,InputReportLength,ReadCompleted,buffer);
}
这是回拨功能
/// < 摘要 >
/// 回调以上。关心它,因为它将在后台线程中从异步读取调用
/// < / summary >
/// < param name =iResult > 异步结果参数< / param < span class =code-summarycomment>>
private void ReadCompleted(IAsyncResult iResult)
{
Byte [] buffer =(字节跨度> [])iResult.AsyncState; // 检索读取缓冲区
尝试
{
MyFileStream.EndRead(iResult); // call end read:抛出读取期间发生的任何异常
尝试
{
HandleDataReceived(buffer); // 将新输入报告传递给更高级别的处理程序
}
finally
{
BeginAsyncRead(); // 完成所有操作后,启动下一次报告的另一次阅读
}
}
catch (IOException) // 如果我们收到IO异常,则设备被删除
{
HandleDeviceRemoved();
if (OnDeviceRemoved!= null )
OnDeviceRemoved( this , new EventArgs());
Dispose();
}
}
我遇到了类似的问题。以下是问题代码的片段。
静态 void Main( string [] args)
{
FileStream stream = new FileStream( test.txt,FileMode.Open) ;
byte [] data = new byte [ 2 ];
var result = stream.BeginRead(data, 0 , 2 ,ReadSuccess,数据);
stream.Close();
Console.ReadLine();
}
static void ReadSuccess(IAsyncResult result)
{
Console.WriteLine( Result {0},(result.AsyncState as byte [])[ 0 ] );
}
我在文件中有AB,并且在控制台中期待65.Writeline。
事实证明,在我调用BeginRead后,流会立即关闭。简单的安排是在关闭流之前调用Console.ReadLine
静态 void Main( string [] args)
{
FileStream stream = new FileStream( test.txt ,FileMode.Open);
byte [] data = new byte [ 2 ];
var result = stream.BeginRead(data, 0 , 2 ,ReadSuccess,数据);
Console.ReadLine();
stream.Close();
}
即使在你的情况下,BeginRead就像在这种情况下一样过去了。
< blockquote>我有同样的问题,我期待这个问题的答案:)谢谢
I'm writing an application to read a USB Cardreader. I'm using the FileStream.BeginRead Async method to read the usb CardReader. but it doesn't seem to return. I was wondering what I am doing wrong here? The PC sees the cardreader as a keybord hid device, I wonder if that is the problem. Can Someone explain to me?
The Callback function only returns if I pull it out of the PC
/// <summary>
/// Initialises the device
/// </summary>
/// <param name="strPath">Path to the device</param>
private void Initialise(String strPath)
{
// Create the file from the device path
MySafeHandle = CreateFile(strPath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open,
EFileAttributes.Overlapped, IntPtr.Zero);
if (!MySafeHandle.IsInvalid) // if the open worked...
{
IntPtr lpData;
if (HidD_GetPreparsedData(MySafeHandle, out lpData))
// get windows to read the device data into an internal buffer
{
try
{
HidCaps hidCaps;
HidP_GetCaps(lpData, out hidCaps); // extract the device capabilities from the internal buffer
InputReportLength = hidCaps.InputReportByteLength; // get the input...
OutputReportLength = hidCaps.OutputReportByteLength; // ... and output report lengths
MyFileStream = new FileStream((SafeFileHandle) MySafeHandle, FileAccess.ReadWrite, InputReportLength,
true); // wrap the file handle in a .Net file stream
BeginAsyncRead(); // kick off the first asynchronous read
}
finally
{
HidD_FreePreparsedData(ref lpData);
// before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
}
}
else // GetPreparsedData failed? Chuck an exception
throw HidDeviceException.GenerateWithWinError("GetPreparsedData failed");
}
else // File open failed? Chuck an exception
{
MySafeHandle.Dispose();
throw HidDeviceException.GenerateWithWinError("Failed to create device file");
}
}
Here is the BeginRead
/// <summary>
/// Kicks off an asynchronous read which completes when data is read or when the device
/// is disconnected. Uses a callback.
/// </summary>
private void BeginAsyncRead()
{
Byte[] buffer = new Byte[InputReportLength];
// put the buff we used to receive the stuff as the async state then we can get at it when the read completes
IAsyncResult result = MyFileStream.BeginRead(buffer, 0, InputReportLength, ReadCompleted, buffer);
}
This is the Callback function
/// <summary>
/// Callback for above. Care with this as it will be called on the background thread from the async read
/// </summary>
/// <param name="iResult">Async result parameter</param>
private void ReadCompleted(IAsyncResult iResult)
{
Byte[] buffer = (Byte[])iResult.AsyncState; // retrieve the read buffer
try
{
MyFileStream.EndRead(iResult); // call end read : this throws any exceptions that happened during the read
try
{
HandleDataReceived(buffer); // pass the new input report on to the higher level handler
}
finally
{
BeginAsyncRead(); // when all that is done, kick off another read for the next report
}
}
catch (IOException) // if we got an IO exception, the device was removed
{
HandleDeviceRemoved();
if (OnDeviceRemoved != null)
OnDeviceRemoved(this, new EventArgs());
Dispose();
}
}
I ran into similar problem. Here is the snippet of problem code.
static void Main(string[] args) { FileStream stream = new FileStream("test.txt",FileMode.Open); byte[] data = new byte[2]; var result = stream.BeginRead(data, 0, 2, ReadSuccess, data); stream.Close(); Console.ReadLine(); } static void ReadSuccess(IAsyncResult result) { Console.WriteLine("Result {0}",(result.AsyncState as byte[])[0]); }
I had AB in the file, and was expecting 65 in the console.Writeline.
It turns out that stream is closed immediately after I called BeginRead. Simple arrangement is to call Console.ReadLine before I close the stream
static void Main(string[] args) { FileStream stream = new FileStream("test.txt",FileMode.Open); byte[] data = new byte[2]; var result = stream.BeginRead(data, 0, 2, ReadSuccess, data); Console.ReadLine(); stream.Close(); }
Even in your case BeginRead moved past just like in this case.
I have the same problem and I expect an answer to this problem:) Thanks
这篇关于为什么FileStream.BeginRead不会结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!