C#中的线程问题

时间:2009-11-04 06:48:31

标签: c# multithreading

有人可以告诉我为什么我的代码无效吗?

class Connection
{
    public static StreamWriter writer;
    public static string SERVER;
    private static int PORT;
    private static string USER;
    private static string NICK;
    private static string CHANNELS;
    private Thread connection;
    private Thread ping;
    public Connection()
    {
        connection = new Thread(new ThreadStart(this.Run));
        ping = new Thread(new ThreadStart(this.Ping));
    }
    public void Start(string server, int port, string ident, string realname, string nick, string channels)
    {
        SERVER = server;
        PORT = port;
        USER = "USER " + ident + " 8 * :" + realname;
        NICK = nick;
        CHANNELS = channels;
        connection.Start();
    }
    public void Ping()
    {
        while (true)
        {
            try
            {
                Connection.writer.WriteLine("PING :" + SERVER);
                Connection.writer.Flush();
                Thread.Sleep(15000);
            }
            catch (Exception e) { Console.WriteLine(e.ToString()); }
        }
    }
    public void Run()
    {
        NetworkStream stream;
        TcpClient irc;
        string inputLine;
        StreamReader reader;
        try
        {
            irc = new TcpClient(SERVER, PORT);
            stream = irc.GetStream();
            reader = new StreamReader(stream);
            writer = new StreamWriter(stream);
            writer.WriteLine(USER);
            writer.Flush();
            writer.WriteLine("NICK " + NICK);
            writer.Flush();
            Thread.Sleep(5000);
            writer.WriteLine("JOIN " + CHANNELS);
            writer.Flush();
            while (true)
            {
                while ((inputLine = reader.ReadLine()) != null)
                {
                    Console.WriteLine(inputLine);
                }
                writer.Close();
                reader.Close();
                irc.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Thread.Sleep(5000);
            Run();
        }
    }
}

它连接到服务器很好,但是ping线程和空洞似乎根本不起作用!而且我不知道为什么,一切看起来都是正确的,除非我遗漏了一些非常明显的东西C

1 个答案:

答案 0 :(得分:4)

您尚未启动ping主题。请调用Start方法。

另一个注意事项 - 不要将Thread.Sleep用于线程/进程同步。根据我的经验,使用它的代码通常很慢,不可靠并且难以维护。使用Monitor类或各种WaitHandle实施(例如AutoResetEvent)或其他。对于客户端/服务器通信,请尝试等待服务器响应您的请求(如果在协议中定义),而不仅仅是超时。

此外,如果您正在启动新线程,请使此线程停止(例如,在您的类的Dispose方法中)或设置IsBackground属性,或者,最好是两者。否则这些线程将阻止您的进程停止。