2011-05-24 77 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."; 
      } 
     ); 
} 
相關問題