Search code examples
c#multithreadingsocketssocket-timeout-exception

Is it possible to reuse a socket after a TimedOut exception?


Simply put, is it possible to reuse a socket after a TimedOut exception has been caught? How can I do it?

Long story:

I have 2 threads, both using the same socket. One is sending packets (let's call it thread A) to a remote server while the other (thread B) is listening for confirmation packets of those sent packets. Thread A will pause (with Monitor.Wait) when some condition is met, waiting for a Monitor.Pulse to continue. When thread B receives a packet, it calls Monitor.Pulse and thread A continues to do it's thing...

The problem is that packets can be lost and thread B will wait indefinitely for a packet that won't receive while thread A is waiting for a pulse. The whole program will "block". My first thought was to set a receive timeout and catch the associated exception. When that happens, I call Monitor.Pulse and thread A can continue while thread B will keep waiting for another packet.

But this doesn't work. When the exception is caught, the socket will close and the app will crash when thread A tries to send a new packet, since they are using the same socket.

How can I prevent this behavior?


Solution

  • TCP Packets cannot be lost (they can but that's on a whole different layer).
    If there is a communication error the socket will close.
    However if you're using UDP Communications and you've selected a receive timeout, there is no reason you shouldn't be able to try again.

    Check This out.
    And Read the remarks here.