Socket.Recieve Failing When Multithreaded

Posted by Qua on Stack Overflow See other posts from Stack Overflow or by Qua
Published on 2010-04-07T20:05:02Z Indexed on 2010/04/07 20:13 UTC
Read the original article Hit count: 288

Filed under:
|
|
|
|

The following piece of code runs fine when parallelized to 4-5 threads, but starts to fail as the number of threads increase somewhere beyond 10 concurrentthreads

int totalRecieved = 0;
int recieved;
StringBuilder contentSB = new StringBuilder(4000);
while ((recieved = socket.Receive(buffer, SocketFlags.None)) > 0)
{
   contentSB.Append(Encoding.ASCII.GetString(buffer, 0, recieved));
   totalRecieved += recieved;
}

The Recieve method returns with zero bytes read, and if I continue calling the recieve method then I eventually get a 'An established connection was aborted by the software in your host machine'-exception. So I'm assuming that the host actually sent data and then closed the connection, but for some reason I never recieved it.

I'm curious as to why this problem arises when there are a lot of threads. I'm thinking it must have something to do with the fact that each thread doesn't get as much execution time and therefore there are some idle time for the threads which causes this error. Just can't figure out why idle time would cause the socket not to recieve any data.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET