[英]BackgroundWorker DoWork function is not being called
I've created a loading form within my C# WinForms application that is shown during long processes.我在我的 C# WinForms 应用程序中创建了一个加载表单,该表单在长时间进程中显示。 I've added a progress bar to my loading form that I would like to update to give some feedback of loading to the user.
我在我的加载表单中添加了一个进度条,我想更新它以向用户提供一些加载反馈。
Within my loading form code, I have created a new BackgroundWorker and added DoWork and ProgressChanged event handlers.在我的加载表单代码中,我创建了一个新的 BackgroundWorker 并添加了 DoWork 和 ProgressChanged 事件处理程序。 The problem is that the backgroundWorker_ProgressChanged is not being called.
问题是没有调用 backgroundWorker_ProgressChanged。 I have inserted break points into the function and they are not caught.
我已经在函数中插入了断点,但它们没有被捕获。
Where am I going wrong?我哪里错了? Any help appreciated.
任何帮助表示赞赏。 Thanks.
谢谢。
frmLoading: frm加载:
public frmLoading()
{
InitializeComponent();
//check if bg worker is null
if (backgroundWorker == null)
{
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
}
backgroundWorker.WorkerReportsProgress = true;
//start
backgroundWorker.RunWorkerAsync();
}
backgroundWorker_DoWork: backgroundWorker_DoWork:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);
backgroundWorker.ReportProgress(i);
}
}
backgroundWorker_ProgressChanged: backgroundWorker_ProgressChanged:
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//update value of progress bar
progressBar1.Value = e.ProgressPercentage;
//set the text of the progress bar
this.Text = e.ProgressPercentage.ToString();
}
Here's how you would do this with Progress<int>
and Task.Run
:以下是使用
Progress<int>
和Task.Run
执行此Task.Run
:
public frmLoading()
{
InitializeComponent();
IProgress<int> progress = new Progress<int>(p =>
{
//update value of progress bar
progressBar1.Value = p;
//set the text of the progress bar
this.Text = p.ToString();
});
Task.Run(async () =>
{
for (int i = 1; i <= 100; i++)
{
await Task.Delay(TimeSpan.FromSeconds(0.1));
progress.Report(i);
}
});
}
Personally I prefer Microsoft's Reactive Framework:我个人更喜欢微软的反应式框架:
public frmLoading()
{
InitializeComponent();
Observable
.Interval(TimeSpan.FromSeconds(0.1))
.Take(100)
.ObserveOn(this)
.Select(p => p + 1)
.Subscribe(p =>
{
//update value of progress bar
progressBar1.Value = p;
//set the text of the progress bar
this.Text = p.ToString();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.