gpt4 book ai didi

c# - C#线程和类问题

转载 作者:行者123 更新时间:2023-12-03 13:22:30 26 4
gpt4 key购买 nike

好的,所以我写了以下代码:

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();
ping.Start();
}
public void Ping()
{
while (true)
{
try
{
writer.WriteLine("PING :" + SERVER);
writer.Flush();
Console.WriteLine("Ping: " + SERVER);
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();
}
}
}

现在,当我引入第一个服务器时,它可以完美地工作:
    Connection one = new Connection();
one.Start("irc.serveraddress.com", 6667, "ident", "realname", "nick", "#channel");

它按时对所有服务器执行ping操作。但是,一旦我引入了第二个连接:
Connection two = new Connection();
two.Start("irc.differentserveraddress.com", 6667, "ident", "realname", "nick", "#channel");

它停止对第一台服务器执行ping操作。并仅对第二台服务器执行ping操作,如何使其继续对两台服务器执行ping操作?

最佳答案

public static string SERVER;

由于此字段是静态的,因此您的类的所有实例都指向同一台服务器。创建第二个实例时,它将在该字段中存储第二个服务器的名称,这意味着第一个实例也使用它。

关于c# - C#线程和类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1672127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com