When setting up my socket for connecting, I wrap the method in a try-catch block..
If a socket exception gets raised, I create a new thread.. sleep for 15 seconds.. and then call the connect method again but this time from another thread. I'm doing this mainly for the sleep method (to avoid using a timer to reconnect) to not hang up the main thread.
Anyhow.. when trying to connect, I write the status to a text box using a method called Write() which just appends the text to the current text with a \n before it...
Because on a failed connect I create a separate thread to call the connect method (which DOES modify a control on the form), I am right to use invoke on the method call right?
Here is my code
private void Connect()
{
try
{
Write("Connecting...");
_ClientSocket.Connect(new IPEndPoint(IPAddress.Loopback, 2500));
Connected = true;
Write("Connected.");
_ClientSocket.BeginReceive(Buffer, 0, Buffer.Length, 0, new AsyncCallback(RecieveCallBack), null);
}
catch (SocketException ex)
{
Write("Connection Failed. Trying again in 15 Seconds...");
Connected = false;
new Thread(delegate()
{
Thread.Sleep(15000);
Invoke((MethodInvoker)delegate
{
this.Connect();
});
}).Start();
}
catch (Exception ex)
{
}
}
I just want to be sure I am doing this in the proper way