开发者

Threading / Linq Class list Issue

I've written a very complex multi-server IRC bot recently, and have encountered an issue.. I have stripped down the code as much as I could which can be viewed here.

My issue is that when I call the Disconnect() the connection is voided instea开发者_StackOverflowd of disconnecting and closing the given server. It also just freezes the calling class instead of stopping the correct instance of the Class.

Any help or experience with a similar issue would be greatly appreciated. Please include code if you can.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜