我想在一個額外的線程中執行Heavy Process
之後可以訪問result
(重進程的返回結果),因爲它主要是期望在進程UI生效期間不需要, 過程完成後會與result
從一個額外的線程返回結果
播放過程中某些搜索,並期待在我的文章中,我得到了有幾種方法到 做到這一點,請提供你知道最好的方法或類似的情況下使用
這就是我要處理的最可能的方法的例子:
public ACollection DoProcess(Document docProcess)
{
ACollection result = new ACollection();
ThreadStart threadStart = delegate
{
result = MyProcess(docProcess);
};
var threadProcess = new Thread(threadStart);
threadProcess.Start();
return result ;
}
其他可能的方法可能是IAsyncResult的,BackgroundWorker的,使用定時器和檢查狀態,而不是將結果返回到方法來處理它,它報告給UI直接在線程安全的方式給我們的UI控件發送...
請給你自己的意見和樣品類似的情況下, 在此先感謝
編輯3:方法 - 基於Brian的回答
LenzCollection myResultCollection = new LenzCollection();
TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
myResultCollection = DoCollect(docProcess);
//Task.WaitAll();
return myResultCollection;
}).ContinueWith((task =>
{
myResultCollection = task.Result;
}), ui);
return myResultCollection;
它仍然沒有等待,將不會得到預期的結果
'while(threadProcess.IsAlive){}'使這個單線程。還有一個CPU-Hog。 – 2012-04-13 10:20:07
我得到了幾分鐘後,編輯,謝謝,但仍需要知道你建議的可重複使用的方法,thr – LastBye 2012-04-13 10:22:06
BackgroundWorker已經得到了所有你問到的功能。那麼爲什麼要重新發明輪子? – Zarat 2012-04-13 10:26:47