C# 任务ContinueWith()未在UI线程上更新光标
我正在开发一个WPF应用程序,我只想在任务运行之前和之后更改光标。我有以下代码:C# 任务ContinueWith()未在UI线程上更新光标,c#,task,C#,Task,我正在开发一个WPF应用程序,我只想在任务运行之前和之后更改光标。我有以下代码: this.Cursor = Cursors.Wait; Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds)).ContinueWith(_ => this.Cursor = Cursors.Arrow); 光标确实会变为等待光标,但在任务完成时不会变回箭头。如果我在ContinueWith()方法中放置断点,它会被命中。但光标
this.Cursor = Cursors.Wait;
Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds)).ContinueWith(_ => this.Cursor = Cursors.Arrow);
光标确实会变为等待光标,但在任务完成时不会变回箭头。如果我在ContinueWith()方法中放置断点,它会被命中。但光标不会变回箭头。为什么?
这是我尝试的老方法。光标变回箭头,但我不想等待()任务
this.Cursor = Cursors.Wait;
Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds)).Wait();
this.Cursor = Cursors.Arrow;
光标更改需要在UI线程上完成。您可以使用接收任务计划程序的:
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory
.StartNew(() => PerformMigration(legacyTrackerIds))
.ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);
或使用以下方法:
我认为您需要使用正确的同步上下文:
this.Cursor = Cursors.Wait;
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext());
Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds))
.ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);
问题是延续需要在UI线程中运行。目前它是在后台线程中完成的
将
TaskScheduler.FromCurrentSynchronizationContext()
添加到ContinueWith
的第二个参数中,使其在UI线程中运行。那么我不应该得到异常吗?@BobHorn您很可能是,但由于它在后台线程中,因此只会使该线程停止运行,不是整个应用程序。当我尝试第一个建议时,我得到一个编译时错误:无法将lambda表达式转换为“System.Delegate”类型,因为它不是委托类型
@BobHorn无论如何都不应该使用该方法。任务的设计使第二种方法成为首选。我刚刚尝试了第二种方法,效果很好。虽然我很想知道为什么第一个选项会出现编译时错误,但我仍然可以工作,所以谢谢!
this.Cursor = Cursors.Wait;
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext());
Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds))
.ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);