I am having an issue canceling a beginReceive call on a timeout. For
example, the following function:
public int ReadBytes(Socket theSock, byte[] arr, int
startByte, int length, int timeout)
{
IAsyncResult result = theSock.BeginReceive(arr, startByte,
length, SocketFlags.None, null, null);
if (result.AsyncWaitHandle.WaitOne(timeout, false) ==
false)
{
throw new Exception("Timeout reading from socket!");
}
return theSock.EndReceive(result);
}
If the wait handle.waitOne returns false, the function throws the
exception as desired. However, if the timeout was 1000 ms and data
came in at 1001 ms, I would detect a timeout, but the bytes would
still have been read, and I would have no way of knowing about it. In
this case if there is a timeout, I will simply call this function
again. However I will have missed the bytes that got read the last
time because I had no way of canceling the endReceive, or no way of
being sure that between the end of the waitOne and throwing of the
exception, data didn't make it into the array.
Basically I would want to add a function like:
if (result.AsyncWaitHandle.WaitOne(timeout, false) ==
false)
{
int numRead =
theSock.endReadAndReturnMeTheNumberReadIfAny();
if (numRead == 0) {
throw new Exception("Timeout reading from
socket!");
}
else {
return numread;
}
}
It would be nice if I could just call theSock.endReceive() but that
will block until data is received, and I need it to be non blocking.
I hope I'm missing something trivial. Perhaps I should just not call
my ReadBytes function unless theSock.Available returns 0?
Thanks,
Ryan