Skip to main content
 首页 » 编程设计

c#之C#中的线程问题

2024年02月24日17zhoujg

有人能告诉我为什么我的代码不起作用吗?

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 Thread 和 voids 似乎根本不起作用!我不知道为什么,一切似乎都是正确的,除非我遗漏了一些非常明显的东西 C

请您参考如下方法:

您还没有启动您的ping 线程。调用它的Start方法。

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

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