In some class I want to load 2 collection asynchronously with Task and stop busyindicator
I try Something like this
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);
But this throw an exception InvalidOperationException:Start may not be called on a continuation task.
Why this doesn’t work, and how can I run continue task after finishing both tasks, without blocking current thread?
Instead of:
I think what you mean is:
Now you can (later) call:
The difference is that we are assigning
loadData1to the outermost task. In your original code, you are assigningloadData1the result ofContinueWith, which is something else (a second task, so that you can wait or continue from the second task).Note: if you want to wait for the inner task, you should capture the result of the
ContinueWithcall into a new variable, and wait on that.