将Backgroundworkerclass替换为worker线程
本文关键字:worker 线程 替换 Backgroundworkerclass | 更新日期: 2023-09-27 18:28:20
我已经使用Backgroundworkerclass来更新我的用户界面元素(Label)。请请检查下面的代码。它运行良好。但我正试图取代Backgroundworkerclass,并使用简单的worker线程来实现同样的目标。我怎样才能做到这一点?任何建议都将不胜感激。感谢
public void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
backgroundWorker1.RunWorkerAsync();
else
label1.Text = "Busy Processing";
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(100);
backgroundWorker1.ReportProgress(i);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
}
delegate void DelegateDoWork(int number);
private void button1_Click(object sender, EventArgs e)
{
new Thread(DoWork).Start();
}
public void ProgressBar(int i)
{
if (label1.InvokeRequired)
{
var d = new DelegateDoWork(ProgressBar);
this.Invoke(d, i);
}
else
label1.Text = i.ToString();
}
public void DoWork()
{
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(100);
ProgressBar(i);
}
}