By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,949 Members | 1,561 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,949 IT Pros & Developers. It's quick & easy.

Canceling beginreceive without closing the socket

P: n/a
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) ==
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) ==
int numRead =
if (numRead == 0) {
throw new Exception("Timeout reading from
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?


Oct 23 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.