如何正确实现BackgroundWorker以通知用户任务正在进行中

时间:2019-06-24 14:40:46

标签: c# multithreading backgroundworker

问题 我使用了https://github.com/zaagan/BioMetrix中的项目,并希望使用BackgroundWorker在长任务中显示进度(例如:获取日志数据大约需要30秒)

我到目前为止所做的事情 1-从工具箱添加了backgroundWorker1 2-在InitializeComponent()之后,我添加了:

 backgroundWorker1.WorkerReportsProgress = true;
 backgroundWorker1.WorkerSupportsCancellation = true;

3-添加了这些功能:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        for (int i = 1; i <= 10; i++)
        {
            if (worker.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {

                System.Threading.Thread.Sleep(500);
                worker.ReportProgress(i * 10);
            }
        }
    }

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


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

我原本希望在从设备中检索日志数据时在主要标题标题文本上查看进度百分比。

1 个答案:

答案 0 :(得分:0)

您需要为事件分配事件处理程序

@extends ('layouts.master')

如果已创建Windows窗体,则需要在Background Worker属性的事件页面中查找并找到DoWork事件,然后为其分配要运行的功能。