First off, you need to add a break so that this:
foreach (Connection connect in connections)
{
if (searching == true)
{
if (connect.SERVERID == ServerID)
{
connect.Stop();
isFound = true;
searching = false;
connections.Remove(connect);
}
}
}
Becomes:
foreach (Connection connect in connections)
{
if (connect.SERVERID == ServerID)
{
connect.Stop();
isFound = true;
connections.Remove(connect);
break;
}
}
Because you are modifying the collection, rather than using the searching == true
clause. Much more efficient.
Next, I would change your thread run to look like this:
public void Run()
{
bool WhileOn = true;
NetworkStream stream;
string inputLine;
StreamReader reader;
try
{
using(TcpClient irc = new TcpClient(SERVER, PORT))
{
...
}
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Thread.Sleep(5000);
}
}
So that your connection gets properly disposed. You should do similarly for your stream.
And finally, I would add an Abort()
call on your thread in the Stop
function after a set timeout. If a TCP socket is blocked by the OS, however, I m not sure if an abort call will interrupt it...