继续任务后所有任务完成任务、继续

2023-09-07 14:05:45 作者:昨夜星辰恰似你

在一些I类要加载2集异步任务,停止BusyIndi​​cator控件

In some class I want to load 2 collection asynchronously with Task and stop 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);

但是,这引发异常 InvalidOperationException异常:开始可能不叫上后续任务

为什么这不工作,我怎么能运行在完成这两项任务后继续工作,而不会阻塞当前线程?

Why this doesn't work, and how can I run continue task after finishing both tasks, without blocking current thread?

推荐答案

相反的:

var loadData1 = new Task<ObservableCollection<Data1>>(GetData1FromService)
               .ContinueWith(t => Data1Collection = t.Result, uiScheduler);

我想你的意思是:

I think what you mean is:

var loadData1 = new Task<ObservableCollection<Data1>>(GetData1FromService);
loadData1.ContinueWith(t => Data1Collection = t.Result, uiScheduler);

现在你可以(后)电话:

Now you can (later) call:

loadData1.Start();

不同的是,我们正在分配 loadData1 到的最外层的的任务。在原来的code,你是分配 loadData1 ContinueWith 的结果,这是别的东西(第二任务,这样就可以等待或在第二任务继续)。

The difference is that we are assigning loadData1 to the outermost task. In your original code, you are assigning loadData1 the result of ContinueWith, which is something else (a second task, so that you can wait or continue from the second task).

请注意:如果要等待内部任务,你应该抓住的 ContinueWith 调入一个新的变量,并等待的的。

Note: if you want to wait for the inner task, you should capture the result of the ContinueWith call into a new variable, and wait on that.