shutting down a socketreceiving thread

  • Thread starter Thread starter Dirk Reske
  • Start date Start date
D

Dirk Reske

Hello,

I have following thread, that reads data from a socket.

private void RecThread()
{
int Len = 0;
byte[] input = new byte[1024];

while((Len = socket.Receive(input)) > 0) //*1
{
...
}
}

If I simply close the socket, I get an exception at *1
And I wont Abort() the thread.
How can I close the connection in a "clean" way?
 
one way to do it is to create a global flag that the worker thread
check can check as it busy loops. if the flag is set, it breaks from
the loop.
 
Catch the SocketException and quit. AFAICT, you must close the socket to
break from the blocking call. Another flag, does not do that after you are
already blocking on receive. However, you should probably loop flag
condition, that way you always check before blocking on receive again.
while ( ! stopped )
{
try
{
len = socket.Receive(input);
// etc..
}
catch( SocketException se) { break; }
}
 
Back
Top