简体   繁体   English

正确地中止BeginRead和BeginWrite的正确方法?

[英]Proper way to prematurely abort BeginRead and BeginWrite?

I have a utility I've written in C# to communicate back and forth with our USB device. 我有一个用C#编写的实用程序,可以与我们的USB设备来回通信。 We use the generic HID driver and wrap a handle to the device in a FileStream object. 我们使用通用的HID驱动程序,并在FileStream对象中包装设备的句柄。 I read/write data using its BeginRead and BeginWrite methods, not because I need asynchronous IO, but simply so I can timeout in case the device enters a noncommunicable state (intentionally or not). 我使用其BeginReadBeginWrite方法读取/写入数据,不是因为我需要异步IO,而是为了在设备进入非通信状态(有意或无意)的情况下可以超时。 All reading/writing is done in my own dedicated IO thread. 所有读/写都在我自己的专用IO线程中完成。

I'm worried that I'm not quite doing things properly, because I've seen a few cases of what I suspect is thread deadlock. 我担心自己做的不是很正确,因为我已经看到一些我怀疑是线程死锁的情况。 Here is a stripped down version of my relevant Read method (which seems to work just fine). 这是我相关的Read方法的简化版本(似乎工作正常)。

if (_readResult == null)
{
  _readResult = _deviceStream.BeginRead(_readBuffer, 0, _readBuffer.Length, null, null);
}

if (_readResult.AsyncWaitHandle.WaitOne(IOTimeout, true))
{
  int bytesRead = _deviceStream.EndRead(_readResult);
  _readResult.AsyncWaitHandle.Close();
  _readResult= null;
  // … Copy bytes to another buffer
}
else
{
  // … Timeout, so retry again in a bit
}

My primary question is how to properly stop an unfinished BeginRead or BeginWrite call if I need to terminate my IO thread and my device is no longer communicating. 我的主要问题是,如果我需要终止IO线程并且设备不再通信,则如何正确停止未完成的BeginReadBeginWrite调用。 I can't just call EndRead because it will sit there and block forever. 我不能只调用EndRead因为它将一直EndRead在那里并永远阻塞。 Is it safe to call Filestream.Close while read/write operations are pending? 在进行读/写操作时调用Filestream.Close是否安全?

I also have to ask, is it safe to have pending read and write operations running simultaneously? 我还必须问一下,让未决的读写操作同时运行是否安全? For example, if my read method times out, can I still go ahead and try to write something? 例如,如果我的读取方法超时,我是否仍然可以继续尝试编写一些东西?

It's hard to reproduce my current deadlock issue, but the really strange part is it seems to start when the IO thread gets "stuck" in my read method. 很难重现当前的死锁问题,但是真正奇怪的是,它似乎是在IO线程被“阻塞”在我的read方法中时开始的。 I'm not sure how that would even happen unless my code isn't working the way I think it is. 我不确定这将如何发生,除非我的代码无法按照我认为的方式工作。

There is no built-in cancellation. 没有内置取消。 Closing the stream is the recommended solution. 建议关闭流。 Just make sure you catch exceptions when you call EndRead... 只要确保在调用EndRead时捕获异常即可。

If you want to use .NET 4.5, there is a new FileStream.ReadAsync that supports cancelation: http://msdn.microsoft.com/en-us/library/hh158566(v=vs.110 ) 如果要使用.NET 4.5,则有一个支持取消的新FileStream.ReadAsynchttp : //msdn.microsoft.com/zh-cn/library/hh158566( v= vs.110

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM