【问题标题】:Task ContinueWith() Not Updating Cursor on UI Thread任务 ContinueWith() 未更新 UI 线程上的光标
【发布时间】:2012-08-31 22:28:58
【问题描述】:

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

this.Cursor = Cursors.Wait;

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

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

这是我尝试的旧方法。光标变回箭头,但我不想 Wait() 完成任务。

this.Cursor = Cursors.Wait;

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

this.Cursor = Cursors.Arrow;

【问题讨论】:

    标签: c# task


    【解决方案1】:

    光标更改需要在 UI 线程上完成。您可以使用带有任务调度程序的overload of ContinueWith

    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); 
    
    Task.Factory
      .StartNew(() => PerformMigration(legacyTrackerIds))
      .ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);
    

    或者使用Dispatcher.Invoke方法:

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

    【讨论】:

    • 那我不应该得到一个例外吗?
    • @BobHorn 你很可能是,但由于它在后台线程中,它只会关闭该线程,而不是整个应用程序。
    • 当我尝试第一个建议时,我得到一个编译时错误:Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
    • @BobHorn 你真的不应该使用那种方法。任务被设计成首选第二种方法。
    • 我刚刚尝试了第二个选项并且成功了。虽然我很想知道为什么第一个选项会出现编译时错误,但我仍然可以正常工作,所以谢谢!
    【解决方案2】:

    我认为你需要使用正确的同步上下文:

    this.Cursor = Cursors.Wait; 
    
    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext()); 
    
    Task.Factory.StartNew(() => PerformMigration(legacyTrackerIds))
                .ContinueWith(_ => this.Cursor = Cursors.Arrow, uiScheduler);
    

    【讨论】:

      【解决方案3】:

      问题是延续需要在 UI 线程中运行。目前它正在后台线程中完成。

      TaskScheduler.FromCurrentSynchronizationContext() 添加到ContinueWith 的第二个参数,使其在UI 线程中运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-20
        • 1970-01-01
        相关资源
        最近更新 更多