/// <summary></summary>
private Byte[] _ReceiveBytes(Int32 size)
{
MemoryStream memory = null;
SocketAsyncEventArgs args = null;
EventHandler<SocketAsyncEventArgs> completed = null;
Exception exception = null;
Int32 last_update = Environment.TickCount;
Boolean finished = false;
Int32 count = 0;
Int32 received = 0;
completed = new EventHandler<SocketAsyncEventArgs>((s, e) =>
{
try
{
count = e.BytesTransferred;
last_update = (count > 0 ? Environment.TickCount : last_update);
memory.Write(e.Buffer, 0, count);
received += count;
finished = (received == size);
if (!finished)
{
count = Math.Min(_ChunkSize, size - received);
args.SetBuffer(new Byte[count], 0, count);
if (!_Socket.ReceiveAsync(e))
{
completed(s, e);
}
}
}
catch (Exception ex)
{
exception = ex;
}
});
using (memory = new MemoryStream())
using (args = new SocketAsyncEventArgs())
{
count = Math.Min(_ChunkSize, size - received);
args.SetBuffer(new Byte[count], 0, count);
args.Completed += completed;
if (!_Socket.ReceiveAsync(args))
{
completed(_Socket, args);
}
while (!finished)
{
Thread.Sleep(_SleepTimeSpan);
if (exception != null)
{
throw new Exception(_ReceiveExceptionMessage, exception);
}
else if (!finished && Environment.TickCount - last_update > _ReceiveTimeout)
{
throw new TimeoutException(_TimeoutExceptionMessage);
}
}
return memory.ToArray();
}
}
Asked
Active
Viewed 365 times
1

Hans Passant
- 922,412
- 146
- 1,693
- 2,536

ChaosPandion
- 77,506
- 18
- 119
- 157
-
3The possibility of posting code for review was discussed in http://stackoverflow.com/questions/405009/so-community-code-reviews . Seeing it happen for real, I must say I doubt you'll get many answers. At least your co-workers would be paid to review code. The idea with the Q/A format is that several persons will have the same question and benefit from well-crafted answers. With reviews, not so much... – Pascal Cuoq Dec 02 '09 at 22:06
-
I suspected as much. I still want to keep it up for a while in case any kind souls are interested. – ChaosPandion Dec 02 '09 at 22:09
-
1You should single out issues which you think are of concern and formulate a generic question, that way we can answer it more generically and the answer maybe used over and over with whoever runs into a similar issue. – Stan R. Dec 02 '09 at 22:09
1 Answers
3
There are problems. "finished" needs to be volatile but can't be, use MRE. Your timeout code can crash on a OverflowException. You're translating exceptions.
But the approach makes no sense, there's no point in waiting for an async operation to complete. Use Socket.ReceiveTimeout to get the timeout exception.

Hans Passant
- 922,412
- 146
- 1,693
- 2,536
-
I don't think finished needs to be volatile in this case. http://stackoverflow.com/questions/59422/is-a-bool-read-write-atomic-in-c – ChaosPandion Dec 09 '09 at 02:08