c# - 后台工作人员未启动
问题描述
我已经实现了我的窗口的后台工作人员 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。如果是这样,它永远不会为空,您也可以从其属性/事件中连接事件处理程序。
尝试这个
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 比较的示例。
推荐阅读
- karate - 如何在空手道中只跳过一个测试用例?
- angular - 简单函数的极端奇怪行为
- c++ - 外部声明的全局对象的 C++ 链接器错误
- javascript - 将 PDF 二进制字符串附加到 JS FormData
- docker - Dockerfile 中的条件复制
- javascript - 在 Facebook 的 Chrome 扩展中禁用页面可见性 API
- javascript - Ajax 不在标签中显示数据
- python-3.x - 在 Nvidia Jetson Nano 中播放视频的 Python 代码
- android - 如何使回调流主要安全?
- ios - UITableViewCell 中的 UICollectionView。捕捉滚动事件