BackgroundWorker和foreach循环

时间:2010-04-26 19:46:19

标签: c# .net backgroundworker

我必须使用backgroundworkers处理循环。

在我开始一个新的循环迭代之前,我需要等到有条不紊的背景工作完成。

在带有isbusy标志的foreach循环中的while循环对我来说似乎不太好。

我应该如何设计这个循环,以便在迭代循环之前等待bg-worker结束

public void AutoConnect()
{
    string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" };
    foreach (string HW in HardwareList)
    {
        if (backgroundWorker1.IsBusy != true)
        {
            backgroundWorker1.RunWorkerAsync(HW);
            // Wait here until backgroundWorker1 finished
        }
    }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = sender as BackgroundWorker;
    string FileName = e.Argument as string;
    try
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
        }
        else
        {
            // Time consuming operation
            ParseFile(Filename);
        }
    }
    catch { }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label1.Text = e.ProgressPercentage.ToString() + " lines";
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(e.Cancelled == true)
    {
        //this.tbProgress.Text = "Canceled!";
    }
    else if(!(e.Error == null))
    {
        //this.tbProgress.Text = ("Error: " + e.Error.Message);
    }
    else
    {
        label1.text = "Done!";
    }
}

2 个答案:

答案 0 :(得分:12)

你正在使用背景工作者。将整个列表传递给后台工作程序并在那里运行foreach循环。

public void AutoConnect()
{
    string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" };
    backgroundWorker1.RunWorkerAsync(HardwareList);
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = sender as BackgroundWorker;
    string[] FileNames = e.Argument as string[];
    int i = 0;

    foreach (string FileName in FileNames)
    {
       ParseFile(FileName);
       worker.ReportProgress(++i);
       if (worker.CancellationPending)
       {
          e.Cancel = true;
          break;
       }
    }
}

答案 1 :(得分:4)

基本思想是将foreach转移到DoWork方法中。这可以使用取消(现在似乎没有效果)。

string[] HardwareList = new string[] { "d1", "d4", "ds1_2", "ds4_2" };
backgroundWorker1.RunWorkerAsync(HardwareList);


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    string[] HardwareList = e.Argument as string[];

    foreach (string HW in HardwareList)
    {
        if (worker.CancellationPending) ...
        .... 
    }
}