【发布时间】:2020-02-13 10:45:46
【问题描述】:
我已经为我的窗口实现了一个后台工作程序 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();
}
【问题讨论】:
-
你确定
backgroundWorker1_DoWork()没有抛出异常吗? -
也许你在某个地方遇到了异常?尝试添加
if( (backgroundWorker1.IsBusy) -
当达到
Progress_Load时是backgroundWorker1 == null吗?该名称听起来像是 Designer 生成的变量。如果设计者创建了对象,则不为空 -
@ThomasWeller no 当达到 Progress_Load 时 backgroundWorker1 不为空
-
@MatthewWatson 是的,代码永远不会到达它在 Load 中的所有内容都很艰难,然后保留在主线程中。
标签: c# wpf backgroundworker