我正在運行後臺線程從數據庫中獲取數據,以便當前線程(UI)不凍結。我正在使用TPL來實現這一點。如何使父線程等待子線程完成 - C#
List<string> _myList1, _myList2;
private void LoadCollections(){
Task db_task = new Task(() => CallDB());
var continuations = db_task.ContinueWith((ant) =>
{
_myList1 = GetDataFromMetaData1();
_myList2 = GetDataFromMetaData2();
});
db_task.Start();
LoadTemplates(); //execute only after 'db_task' completes execution
}
在上面的代碼
CallDB()
- 獲取從在元數據數據庫中,並將其存儲的數據。在這種情況下,請考慮它是一個字符串列表。 (說List<string> MetaStrings
)
GetDataFromMetaData1()
和GetDataFromMetaData2()
- 獲取2個單獨的名單,這是MetaStrings
子目錄。
現在我只希望在加載_myList1
和_myList2
之後,即db_task
已經完成執行之後,執行函數LoadTemplates
。目前,我正在使用這個
while(_mylist1==null && _mylist2==null)
Thread.Sleep(50);
LoadTemplates();
但是,當UI線程進入睡眠狀態時,這顯然會凍結UI。那麼任何人都可以提出一種有效的方法來處理這種情況?
PS:LoadTemplates()
初始化一些ObservableCollection
變量。如果在子線程中調用LoadTemplates()
,則db_task
則引發以下錯誤This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread
。因此產生了線程等待的情況。
不能使用異步&等待? – terrybozzio 2014-10-19 23:28:32
實際上'LoadCollections'函數是一個信使事件。換句話說,當用戶點擊UI上的一個按鈕時,ViewModel註冊來調用'LoadCollections'。所以在這種情況下,我有點失落了如何使用async/await。 – SohamC 2014-10-19 23:32:10
不能使用Task.WaitAll(任務); – user1274820 2014-10-20 00:04:18