阻塞监听防止断开连接

blocking listen prevents disconnect

问题概述:

我需要连接到 IRC 服务器。连接后,程序将向通道发送一条消息,并通过多条线路返回响应。我需要阅读这些行并将其存储在一个变量中以备后用。消息末尾的特殊字符 (]) 将定义多行消息的结尾。一旦我们收到这个字符,IRC 会话应该断开并且处理应该继续。

情况:

我正在使用 Smartirc4net 库。调用 irc.Disconnect() 大约需要 40 秒来断开会话。一旦我们收到 ] 字符,会话应该断开,Listen() 不应该阻塞,程序的其余部分应该继续 运行.

研究:

我发现了这个:smartirc4net listens forever, can't exit thread,我认为这可能是同一个问题,但是,我不确定我需要做什么来解决这个问题。

代码:

public class IrcCommunicator
    {
        public IrcClient irc = new IrcClient();

        string data;

        public string Data { get { return data; } }


        // this method we will use to analyse queries (also known as private messages)
        public void OnQueryMessage(object sender, IrcEventArgs e)
        {
            data += e.Data.Message;
            if (e.Data.Message.Contains("]"))
            {
                irc.Disconnect();  //THIS TAKES 40 SECONDS!!!

            }
        }

        public void RunCommand()
        {
            irc.OnQueryMessage += new IrcEventHandler(OnQueryMessage);

            string[] serverlist;
            serverlist = new string[] { "127.0.0.1" };
            int port = 6667;
            string channel = "#test";

            try
            {
                irc.Connect(serverlist, port);
            }
            catch (ConnectionException e)
            {
                // something went wrong, the reason will be shown
                System.Console.WriteLine("couldn't connect! Reason: " + e.Message);
            }

            try
            {
                // here we logon and register our nickname and so on 
                irc.Login("test", "test");
                // join the channel
                irc.RfcJoin(channel);
                irc.SendMessage(SendType.Message, "test", "!query");

                // here we tell the IRC API to go into a receive mode, all events
                // will be triggered by _this_ thread (main thread in this case)
                // Listen() blocks by default, you can also use ListenOnce() if you
                // need that does one IRC operation and then returns, so you need then 
                // an own loop 

                irc.Listen();

                // when Listen() returns our IRC session is over, to be sure we call
                // disconnect manually
                irc.Disconnect();
            }
            catch (Exception e)
            {
                // this should not happen by just in case we handle it nicely
                System.Console.WriteLine("Error occurred! Message: " + e.Message);
                System.Console.WriteLine("Exception: " + e.StackTrace);
            }
        }

    }




        IrcBot bot = new IrcBot();
        bot.RunCommand();

        ViewBag.IRC = bot.Data;

如你所见,一旦这个 感谢您花时间查看这段代码并阅读我的问题描述。如果您有任何想法或其他建议,请告诉我。

麦克

在 irc.Disconnect();

之前,通过在 OnQueryMessage() 中调用 RfcQuit(),我能够立即成功断开连接