开发者

Implementing BackgroundWorker's RunWorkerCompleted using Tasks

I have a WPF MVVM application. In one of the ViewModels, I have the following:

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

    Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 100; ++i)
            {
  开发者_Go百科              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.";
            }
        );
}

When I click the button bound to the GoCommand, I see the progress bar move from 1-100. When the ContinueWith executes DoSecondTask, though, that task runs in the UI thread. How can I change the DoSecondTask function to run the second for loop in a new thread (or outside of the UI thread)?


I found the solution in this answer. It's interesting to note that this does not work:

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.";
            }
        );
}

But this does:

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.";
            }
        );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜