views:

69

answers:

1

Ok, so ive been writing a very complex multiserver irc bot recently, and ive encountered an issue.. i stipped down the code as much as i could because its very large, the full code is here: http://pastie.org/691449.txt

so what my issue is, when i call the Disconnect() void in Connection, instead of disconnecting and closing the given server, it just freezes the calling class instead of stopping the correct instance of the Class. Any help would be greatly appriciated ~ code examples for answers when possible please

+1  A: 

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...

John Gietzen
is that everything?? and will that solve my problem?
Xavier
This will fail, because you are trying to modify the collection while it is being enumerated: connections.Remove(connect). You will have to use a for or while loop and iterate manually to be able to modify the collection, and you will not be able to use the IEnumerable interface.
jrista
@jrista: No, it should be okay, because after removing the idea it breaks out of the loop; it doesn't iterate again.
Jon Skeet
@Xavier: I'm not sure. I seem to remember that it is almost impossible to disconnect mid-read. I would give this a go, though.
John Gietzen