[英]Threading issue in C#
誰能告訴我為什么我的代碼不起作用?
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線程和空洞似乎根本不起作用! 我不知道為什么,一切似乎都是正確的,除非我遺漏了一些非常明顯的東西
你還沒有啟動ping
線程。 調用它的Start
方法。
另一個注意事項 - 不要使用Thread.Sleep
進行線程/進程同步。 根據我的經驗,使用它的代碼通常很慢,不可靠並且難以維護。 使用Monitor
類或各種WaitHandle
實現(例如AutoResetEvent
)或其他。 對於客戶端/服務器通信,請嘗試等待服務器響應您的請求(如果在協議中定義),而不僅僅是超時。
此外,如果您正在啟動新線程,請使此線程停止(例如,在您的類的Dispose
方法中)或設置IsBackground
屬性,或者,最好是兩者。 否則這些線程將阻止您的進程停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.