Ars*_*yan 5 c# android .net-4.0 task android-asynctask
在某些类中,我想与Task异步加载2个集合并停止busyindicator
我尝试这样的东西
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
WaitingIndicatorViewModel.IsBusy = true;
var loadData1 = new Task<ObservableCollection<Data1>>(GetData1FromService).ContinueWith(t => Data1Collection = t.Result, uiScheduler);
var loadData2 = new Task<ObservableCollection<Data2>>(GetData2FromService).ContinueWith(t => Data2Collection = t.Result, uiScheduler);
Task.Factory.StartNew(() =>{
loadData1.Start();//<--Exception here
loadData2.Start();
Task.WaitAll(loadData1, loadData2);
})
.ContinueWith(o => WaitingIndicatorViewModel.IsBusy = false, uiScheduler);
Run Code Online (Sandbox Code Playgroud)
但这引发了例外 InvalidOperationException:Start may not be called on a continuation task.
为什么这不起作用,如何在完成两个任务后运行继续任务,而不阻塞当前线程?
Mar*_*ell 15
代替:
var loadData1 = new Task<ObservableCollection<Data1>>(GetData1FromService)
.ContinueWith(t => Data1Collection = t.Result, uiScheduler);
Run Code Online (Sandbox Code Playgroud)
我想你的意思是:
var loadData1 = new Task<ObservableCollection<Data1>>(GetData1FromService);
loadData1.ContinueWith(t => Data1Collection = t.Result, uiScheduler);
Run Code Online (Sandbox Code Playgroud)
现在你可以(稍后)打电话:
loadData1.Start();
Run Code Online (Sandbox Code Playgroud)
所不同的是,我们正在分配loadData1到最外面的任务.在你的原代码,您要分配loadData1的结果ContinueWith,这是别的东西(第二个任务,让你可以等待,或从继续第二个任务).
注意:如果你想等待内部任务,你应该捕捉的结果ContinueWith呼叫到一个新的变量,并等待那个.