任务ContinueWith()不更新UI线程上的光标

Bob*_*orn 5 c# task

我正在开发一个WPF应用程序,我只想在任务运行之前和之后更改光标.我有这个代码:

this.Cursor = Cursors.Wait;

Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds)).ContinueWith(_ => this.Cursor = Cursors.Arrow);
Run Code Online (Sandbox Code Playgroud)

光标确实更改为等待光标,但在任务完成时它不会更改回箭头.如果我在ContinueWith()方法中放置一个断点,它就会被击中.但光标不会变回箭头.为什么?

这是我尝试它的旧方法.光标变回箭头,但我不想等待任务的Wait().

this.Cursor = Cursors.Wait;

Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds)).Wait();

this.Cursor = Cursors.Arrow;
Run Code Online (Sandbox Code Playgroud)

Ric*_*lly 11

需要在UI线程上完成游标更改.您可以使用ContinueWith重载来获取任务调度程序:

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); 

Task.Factory
  .StartNew(() => PerformMigration(legacyTrackerIds))
  .ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);
Run Code Online (Sandbox Code Playgroud)

或者使用Dispatcher.Invoke方法:

Task.Factory
  .StartNew(() => PerformMigration(legacyTrackerIds))
  .ContinueWith(_ => { Dispatcher.Invoke(() => { this.Cursor = Cursors.Arrow; }); });
Run Code Online (Sandbox Code Playgroud)