2012-02-08 71 views
1

我有Windows窗體。在構造函數中服務器線程開始正確完成服務器線程

thServer = new Thread(ServerThread); 
thServer.Start(); 

在服務器線程有TCP監聽循環:

while (true) { 
    TcpClient client = server.AcceptTcpClient(); 
    ... 
    } 

當我關閉的主要形式,該線程將繼續等待的TcpClient的請求。我怎樣才能停止這個例程? 謝謝。

+0

BTW,你不需要添加 「(C#)」 到您的標題。這就是標籤的用途。 – 2012-02-08 14:16:30

回答

1
public partial class Form1 : Form 
{ 
    Thread theServer = null; 

    public Form1() 
    { 
     InitializeComponent(); 

     this.FormClosed += new FormClosedEventHandler(Form1_FormClosed); 

     theServer = new Thread(ServerThread); 
     theServer.IsBackground = true; 
     theServer.Start(); 

    } 

    void ServerThread() 
    { 
     //TODO 
    } 

    private void Form1_FormClosed(object sender, FormClosedEventArgs e) 
    { 
     theServer.Interrupt(); 
     theServer.Join(TimeSpan.FromSeconds(2)); 
    } 
} 
+0

我想這是正確的代碼。但是,當我關閉我的應用程序func Form1_FormClosed()不被調用..(我在調試時檢查) – 2012-02-08 14:47:28

+1

已更新以顯示如何捕獲FormClosed事件。 – ahazzah 2012-02-08 14:50:57

1

最簡單的方法是,以紀念線程作爲一個後臺線程 - 那麼它不會讓你的進程在運行,當你的主窗體關閉:

thServer = new Thread(ServerThread); 
thServer.IsBackground = true; 
thServer.Start(); 

MSDN: Thread.IsBackground

0

一個辦法是增加充當while循環條件的標誌。 當然,你也可以設置線程對象的IsBackground屬性,但你可能想要執行一些清理代碼。

例子:

class Server : IDisposable 
{ 
    private bool running = false; 
    private Thread thServer; 

    public Server() 
    { 
     thServer = new Thread(ServerThread); 
     thServer.Start(); 
    } 

    public void Dispose() 
    { 
     running = false; 
     // other clean-up code 
    } 

    private ServerThread() 
    { 
     running = true; 
     while (running) 
     { 
      // ... 
     } 
    } 
} 

用法:

using (Server server = new Server()) 
{ 
    // ... 
} 
0

請指示形式特殊的布爾變量即將關閉。在後臺線程中檢查它的值,並在它爲真時中斷循環。在主窗體中設置變量值爲true,並調用thServer.Join()來等待線程完成。然後您可以安全地關閉 表單。事情是這樣的:

在形式收處理程序:

abortThread = true; 
thServer.Join(); 

在服務器線程循環:

while (true) 
{ 
    if (abortThread) 
     break; 

    TcpClient client = server.AcceptTcpClient(); 
    ... 
} 
+1

如果已經調用了「AcceptTcpClient」,則這並不能解決問題。 – alf 2012-02-08 14:28:32

+0

我試過了。如果沒有客戶端,服務器線程將處於等待模式 – 2012-02-08 14:33:44