The correct way to prematurely interrupt BeginRead and BeginWrite?

I have a utility that I wrote in C # to exchange data with our USB device. We use the general HID driver and transfer the device descriptor to the object FileStream. I read / write data using BeginReadand methods BeginWrite, and not because I need asynchronous I / O, but just so that I can time out if the device goes into a non-infectious state (intentionally or not). All read / write is done in my own dedicated I / O stream.

I am worried that I am not doing the right thing because I have seen several cases of what I suspect is a dead end. Here is a stripped down version of my respective method Read(which seems to work very well).

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 main question is how to properly stop an unfinished call, BeginReador BeginWriteif I need to stop my I / O flow, and my device stops communicating. I can't just call EndReadbecause he will sit and block forever. Is it safe to call Filestream.Closeduring read / write operations?

I must also ask: is it safe to have pending read and write operations at the same time? For example, if my reading method does not work, can I continue and try to write something?

, , , , - "" . , , , .

+4
1

. - . , , EndRead...

.NET 4.5, FileStream.ReadAsync, : http://msdn.microsoft.com/en-us/library/hh158566(v=vs.110)

+6

All Articles