【问题标题】:Implementing BackgroundWorker's RunWorkerCompleted using Tasks使用Tasks实现BackgroundWorker的RunWorkerCompleted
【发布时间】:2011-05-24 15:00:07
【问题描述】:

我有一个 WPF MVVM 应用程序。在其中一个 ViewModel 中,我有以下内容:

this.GoCommand = new RelayCommand(() =>
{
    var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

    Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 100; ++i)
            {
                this.Progress = i + 1;
                Thread.Sleep(30);
            }
        }).ContinueWith(task =>
            {
                // should act like RunWorkerCompleted
                this.DoSecondTask();
            },
            scheduler
        );
});

private void DoSecondTask()
{ 
    Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 100; ++i)
            {
                // repeated task for simplicity
                this.Progress = i + 1;
                Thread.Sleep(30);
            }
        }).ContinueWith(task =>
            {
                this.Status = "Done.";
            }
        );
}

当我单击绑定到 GoCommand 的按钮时,我看到进度条从 1 移动到 100。但是,当 ContinueWith 执行 DoSecondTask 时,该任务在 UI 线程中运行。如何更改 DoSecondTask 函数以在新线程(或 UI 线程之外)中运行第二个 for 循环?

【问题讨论】:

    标签: .net c#-4.0 backgroundworker task


    【解决方案1】:

    我在this 答案中找到了解决方案。有趣的是,这不起作用

    private void DoSecondTask()
    { 
        Task.Factory.StartNew(_ =>
            {
                for (int i = 0; i < 100; ++i)
                {
                    // repeated task for simplicity
                    this.Progress = i + 1;
                    Thread.Sleep(30);
                }
            }, TaskScheduler.Default).ContinueWith(task =>
                {
                    this.Status = "Done.";
                }
            );
    }
    

    但这确实

    private void DoSecondTask()
    { 
        Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 100; ++i)
                {
                    // repeated task for simplicity
                    this.Progress = i + 1;
                    Thread.Sleep(30);
                }
            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith(task =>
                {
                    this.Status = "Done.";
                }
            );
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      相关资源
      最近更新 更多