2016-06-17 32 views
-1

在doowrk事件:我如何取消/停止背景工作?

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
     { 
      BackgroundWorker worker = sender as BackgroundWorker; 
      _stopwatch.Restart(); 
      DirSearch(@"d:\c-sharp", "*.cs", "Form1"); 
      _stopwatch.Stop(); 
     } 

的问题是,我打电话DirSearch在DoWork的事件,所以我可以工作者不能传递到DirSearch。

如果我将工人传递给DirSearch然后我需要在DirSearch做:

if (worker.CancellationPending == true) 
       { 
        e.Cancel = true; 
        break; 
       } 

但E不是在DirSearch存在。

private void DirSearch(string root, string filesExtension,string textToSearch) 
     { 
      int numberoffiles = 0; 
      int numberofdirs = 0; 
      string[] filePaths = Directory.GetFiles(root, filesExtension, SearchOption.AllDirectories); 
      for (int i = 0; i < filePaths.Length; i++) 
      { 
       List<MyProgress> prog = new List<MyProgress>(); 
       int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0; 
       if (var == 1) 
       { 
        string filename = filePaths[i]; 
        numberoffiles ++; 
        prog.Add(new MyProgress { Report1 = filename, Report2 = numberoffiles.ToString() }); 
        backgroundWorker1.ReportProgress(0, prog); 
        Thread.Sleep(100); 
       } 
       numberofdirs ++; 
       label1.Invoke((MethodInvoker)delegate 
          { 
           label1.Text = numberofdirs.ToString(); 
           label1.Visible = true; 
          }); 
      } 
     } 
+0

就跳出for循环中时,它的取消。 – LarsTech

+0

然后将它传递给DirSearch,正是这样的例子是文档。 https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 – Paparazzi

+0

格式在左侧。为什么即使有一个后台工作者,如果你要报告和更新每一个循环? – Paparazzi

回答

3

如果你想使用一个BackgroundWorker,你就需要通过DoWorkEventArgsBackgroundWorker到您的功能。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 
    _stopwatch.Restart(); 
    DirSearch(@"d:\c-sharp", "*.cs", "Form1", worker, e); 
    _stopwatch.Stop(); 
} 
private void DirSearch(string root, string filesExtension,string textToSearch, BackgroundWorker worker, DoWorkEventArgs e) 
{ 
    int numberoffiles = 0; 
    int numberofdirs = 0; 
    string[] filePaths = Directory.GetFiles(root, filesExtension, SearchOption.AllDirectories); 
    for (int i = 0; i < filePaths.Length; i++) 
    { 
     if (worker.CancellationPending == true) 
     { 
      e.Cancel = true; 
      return; 
     } 

     List<MyProgress> prog = new List<MyProgress>(); 
     int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0; 
     if (var == 1) 
     { 
      string filename = filePaths[i]; 
      numberoffiles ++; 
      prog.Add(new MyProgress { Report1 = filename, Report2 = numberoffiles.ToString() }); 
      backgroundWorker1.ReportProgress(0, prog); 
      Thread.Sleep(100); 
     } 
     numberofdirs ++; 
     label1.Invoke((MethodInvoker)delegate 
        { 
         label1.Text = numberofdirs.ToString(); 
         label1.Visible = true; 
        }); 
    } 
} 

这里是一个快速reimplmentation使用异步/等待和Task.Run

CancellationTokenSource source = new CancellationTokenSource(); 

private async Task SearchDirectories() 
{ 
    if (source != null) 
    { 
     //Cancel the previously running instance. 
     source.Cancel(); 
    } 
    source = new CancellationTokenSource(); 
    var foundProgress = new Progress<MyProgress>(/* Some code here*/); 
    var totalProgress = new Progress<int>(numberofdirs => 
    { 
      label1.Text = numberofdirs.ToString(); 
      label1.Visible = true; 
    }); 

    try 
    { 
     _stopwatch.Restart(); 
     await Task.Run(() => DirSearch(@"d:\c-sharp", "*.cs", "Form1", source.Token, foundProgress, totalProgress), source.Token); 
     _stopwatch.Stop(); 

     //Do any code here you had in BackgroundWorker.RunWorkerCompleted 
    } 
    catch (OperationCanceledException) 
    { 
     //Do any special code here if it was canceled. 
    } 

} 

private void DirSearch(string root, string filesExtension, string textToSearch, CancellationToken token, IProgress<MyProgress> foundProgress, IProgress<int> totalProgress) 
{ 
    int numberoffiles = 0; 
    int numberofdirs = 0; 
    string[] filePaths = Directory.GetFiles(root, filesExtension, SearchOption.AllDirectories); 
    for (int i = 0; i < filePaths.Length; i++) 
    { 
     token.ThrowIfCancellationRequested(); 

     int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0; 
     if (var == 1) 
     { 
      string filename = filePaths[i]; 
      numberoffiles++; 
      var prog = new MyProgress { Report1 = filename, Report2 = numberoffiles.ToString() }; 
      foundProgress.Report(prog); 
     } 
     numberofdirs++; 
     totalProgress.Report(numberofdirs); 
    } 
}