2011-05-24 69 views
1

我有一个WPF MVVM应用程序。在的ViewModels之一,我有以下几点:使用任务实现BackgroundWorker的RunWorker

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循环?

回答

2

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