-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;
});
}
}
就跳出for循環中時,它的取消。 – LarsTech
然後將它傳遞給DirSearch,正是這樣的例子是文檔。 https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 – Paparazzi
格式在左側。爲什麼即使有一個後臺工作者,如果你要報告和更新每一個循環? – Paparazzi