2009-11-04 102 views
0

好了,所以我有這樣的代碼,我寫道: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(); 
     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(); 
     } 
    } 
} 
現在

,即workes完美,當我推出的第一臺服務器:

Connection one = new Connection(); 
    one.Start("irc.serveraddress.com", 6667, "ident", "realname", "nick", "#channel"); 

要乒服務器上時間,一切..但只要我介紹第二個連接:

Connection two = new Connection(); 
two.Start("irc.differentserveraddress.com", 6667, "ident", "realname", "nick", "#channel"); 

它停止ping第一臺服務器。並只是ping第二臺服務器,我怎麼能這樣做,它會繼續ping兩臺服務器?

+0

我懷疑靜態屬性與它有關。兩個Ping線程都使用了與引入第二個連接時相同的屬性。 – 2009-11-04 07:17:28

回答

2
public static string SERVER; 

由於該字段是靜態的,因此該類的所有實例都指向同一臺服務器。當您創建第二個實例時,它會在此字段中存儲第二個服務器的名稱,這意味着第一個實例也會使用它。

1

刪除所有「靜態」。你應該關閉連接,關閉類對象,而不是創建一個實例。