2011-08-22 214 views
1

我有一個啓動函數,它根據設置是否成功調用一個返回布爾值的函數。如果成功則爲真,如果失敗則爲假。我想在新線程上啓動該函數,然後檢查函數的狀態:這裏是代碼。快速多線程問題

System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(StartAdapter)); 
thread.Start(); 

我的問題是,如何在這種情況下,我會檢查startadapter方法的返回狀態?因爲我的朋友告訴我,我不知道返回狀態,因爲它是在另一個線程開始,卻又想:

System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(StartAdapter)); 
thread.Start(); 
bool result = StartAdapter(); 

會調用該函數的兩倍,這是我不希望任何。有人對此有所瞭解嗎?

在這種情況下,我將如何檢查從startadapter函數返回的布爾值?

.NET 3.5

+0

這取決於你想要對結果做什麼。爲什麼StartAdapter本身不能處理它?但是請使用任務或ThreadPool。 –

+0

感謝您的意見,@亨克霍爾特曼。我需要知道它是否設置正確,否則我可以提示用戶是否要重試或繼續使用該程序。我打算改變一個標誌,這將觸發在GUI上啓用按鈕的功能,允許用戶重試該啓動。 –

+1

適用於UI特殊規則。您將需要WinForms Invoke或WPF Dispatch。更容易:使用Backgroundworker。 –

回答

5

對於這種情況存在Task<T>class,關於線程池執行(例如),並讓你知道的返回值,它的完成

後,只需使用:



var task = TaskFactory&ltyourResultType>.StartNew(StartAdapter); 
Action&ltyourResultType> actionAfterResult = ...; // whatever you have to do 
task.ContinueWith(actionAfterResult); 

// or: 
var result = task.Result; // this will block till the result is computed 

// or another one of the alternatives you can learn about on MSDN (see link above) 

+1

請注意,如果'Task'在調用'ContinueWith()'之前完成,則回調將不會觸發。 – dlev

+0

不幸的是,我使用Visual Studio C#,其中.NET框架爲3.5,而您所指的類僅在4中受支持。儘管如此,感謝您的輸入,您是否知道其他任何方式? –

+1

@ tf.rz不要害怕!閱讀此:http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/aa1dd834-3c3d-409b-907e-196ee8f427bf – dlev