首页 > 解决方案 > 后台工作人员未启动

问题描述

我已经实现了我的窗口的后台工作人员 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();
}

标签: c#wpfbackgroundworker

解决方案


加载表单时可能不为空。您可能已经通过设计器添加了 BackgroundWorker。如果是这样,它永远不会为空,您也可以从其属性/事件中连接事件处理程序。

尝试这个

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();
}

在 WPFDispatcher.BeginInvoke(DispatcherPriority.Background, workAction);中是另一种选择,因为报告进度在您的方案中没有多大用处。这里是 Dispatcher 和 Background worker 比较的示例


推荐阅读