在doowrk活动中:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
_stopwatch.Restart();
DirSearch(@"d:\c-sharp", "*.cs", "Form1");
_stopwatch.Stop();
}
问题是我在dowork事件中调用DirSearch所以我无法将工作者传递给DirSearch。
如果我将工作人员传递给DirSearch,那么我需要在DirSearch中做:
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
但是DirSearch中不存在e。
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 :(得分:3)
如果您想使用BackgroundWorker,则需要将BackgroundWorker
和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;
});
}
}
传递给您的函数。
Task.Run
这是使用async / await和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);
}
}
StringBuilder strData = new StringBuilder();
ReferenceDocument.SaveCopyAs(strSomeTempFile);
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended properties=\"Excel 8.0;IMEX=1;HDR=NO\"", strSomeTempFile);
var cnn = new OleDbConnection(cnnStr);
try
{
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach(DataRow schemaRow in schemaTable.Rows)
{
string worksheetName = schemaRow["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheetName);
var da = new OleDbDataAdapter(sql, cnn);
var dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
foreach (DataColumn col in dt.Columns)
{
var value = row[col.ColumnName];
if (!(value is System.DBNull)) strData.AppendLine(value.ToString());
}
}
}
catch (Exception e)
{
// handle error
throw;
}
finally
{
cnn.Close();
}
return strData;