后台工作者未启动

Background worker not starting

我已经为我的 window 实现了一个后台工作者 onLoad。到达 Progress_Load 中的代码,但此后不会调用 DoWork 函数。函数 excel.Read() 将一个相当大的 excel 表格读入列表,这大约需要 1.5 分钟,这就是为什么我想同步执行它。

public List<Part> partList = new List<Part>() { };
//boolean that will be set when the backgroundworker is done
public bool listRead = false;

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    _Excel excel = new _Excel();
    partList = excel.Read();
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Message m;
    if (e.Cancelled == true)
    {
        m = new Message("The operation has been canceld!", "Canceled");
        this.Close();
    }
    else if (e.Error != null)
    {
        Error er = new Error("Error: " + e.Error.Message, "Error!");
        this.Close();
    }
    else
    {
        listRead = true;
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //Change the value of the ProgressBar to the BackgroundWorker progress.
    progressBar1.Value = e.ProgressPercentage;
    //Set the text.
    this.Text = e.ProgressPercentage.ToString();
}

private void Progress_Load(object sender, EventArgs e)
{

    if (backgroundWorker1 == null)
    {
        backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    }
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true;
    backgroundWorker1.RunWorkerAsync();
}

可能加载表单时不为空。您可能已经通过设计器添加了 BackgroundWorker。如果是这样,它永远不会为空,您也可以从其 Properties/Events.

连接事件处理程序

试试这个

private void Progress_Load(object sender, EventArgs e)
{

    if (backgroundWorker1 == null)
    {
        backgroundWorker1 = new BackgroundWorker();
    }

    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true;
    backgroundWorker1.RunWorkerAsync();
}

在 WPF 中 Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction); 是另一种选择,因为报告进度在您的方案中用处不大。这里 example for Dispatcher and Background worker comparison.