2011-02-15 157 views
0

我有一個workerthread,它需要兩個輸入框的用戶名和密碼,但如果用戶名/密碼爲空,我想停止它。如何停止/啓動線程?

我試過使用Suspend()方法,但intellisens告訴我它已過時。我如何停止/啓動一個線程?

+0

線程如何「取」用戶名和密碼?你如何開始線程?你能不*啓動線程? –

+1

更有趣的是,爲什麼你正在產生一個線程來做到這一點... –

+1

你可以顯示你到目前爲止的代碼嗎?這可能會讓你更清楚你想達到什麼。 –

回答

2

我不明白你爲什麼需要一個線程來獲得輸入,但是你應該在任務結束後通過返回來停止線程。你不應該殺死它。

if(!validInput(username, password)) 
    return; // et voila 

編輯:如果你試圖同步多個線程(如暫停/恢復或等待/通知在Java),然後從MSDN此信息可能非常有用:

Thread.Suspend一直棄用。 請使用 System.Threading中的其他類,如Monitor, Mutex,Event和Semaphore, 同步線程或保護 資源。 http://go.microsoft.com/fwlink/?linkid=14202

1

可以使用Thread.Abort()方法,但它可能會導致不一致的共享狀態,由於劇烈終止線程。更好的選擇是通過使用CancellationToken來使用協作終止。

// Create a source on the manager side 
var source = new CancellationTokenSource(); 
var token = source.Token; 

var task = Task.Factory.StartNew(() => 
{ 
    // Give the token to the worker thread. 
    // The worker thread can check if the token has been cancelled 
    if (token.IsCancellationRequested) 
    return; 

    // Not cancelled, do work 
    ... 
}); 

// On the manager thread, you can cancel the worker thread by cancelling the source 
source.Cancel(); 
+1

Thread.Abort()是邪惡的 –

+0

這就是爲什麼他提到它@steve – atamanroman