ContinueWith () task Do not update cursor in UI thread

I am working on a WPF application and I just want to change the cursor before and after the task starts. I have this code:

this.Cursor = Cursors.Wait;

Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds)).ContinueWith(_ => this.Cursor = Cursors.Arrow);

The cursor actually changes to a wait cursor, but when the task is completed, it does not return to the arrow. If I set a breakpoint in the ContinueWith () method, it will hit. But the cursor does not return to the arrow. Why?

It was the old way that I tried it. The cursor has changed to an arrow, but I do not want to wait () for the task.

this.Cursor = Cursors.Wait;

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

this.Cursor = Cursors.Arrow;
+5
source share
3 answers

The cursor change must be done in the user interface thread. You can use Dispatcher.Invoke overload :

Task.Factory
  .StartNew(() => PerformMigration(legacyTrackerIds))
  .ContinueWith(_ => { Dispatcher.Invoke(() => { this.Cursor = Cursors.Arrow; }); });
+10
source

, :

this.Cursor = Cursors.Wait; 

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext()); 

Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds))
            .ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);
+2

The problem is that the continuation must be done in the user interface thread. This is currently being done in the background thread.

Add TaskScheduler.FromCurrentSynchronizationContext()to the second parameter ContinueWithso that it runs in the user interface thread.

+2
source

All Articles