In an application I'm developing, I have the need to handle a socket-timeout differently from a general socket exception. The problem is that many different issues result in a SocketException
and I need to know what the cause was.
There is no inner exception reported, so the only information I have to work with is the message:
"A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond"
This question has a general and specific part:
- is it acceptable to write conditional logic based upon the textual representation of an exception?
- Is there a way to avoid needing exception handling?
Example code below...
try
{
IPEndPoint endPoint = null;
client.Client.ReceiveTimeout = 1000;
bytes = client.Receive(ref endPoint);
}
catch( SocketException se )
{
if ( se.Message.Contains("did not properly respond after a period of time") )
{
// Handle timeout differently..
}
}
I'm wanting to cease the "wait for new data" every now and again, so that my worker thread can look to see whether it has been asked to gracefully close - I would rather avoid cross-thread termination of the socket to provide this mechanism.