我知道它有3种方法。在我的程序中,我有一个发送消息的方法。通常会很晚,并且程序有时根本不会响应按钮按下而发送消息。有时,它比我预期晚了 5 秒,程序就会冻结。我想用一个
BackgroundWorker
按预期发送消息并让程序始终正常运行。我有在按钮处理程序中发送消息的代码。现在我应该把这个等效的代码放在哪里?我希望所有这些仍然可以通过按下按钮来处理。
这是合适的处理程序吗?
backgroundWorker1.RunWorkerAsync();
并在:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {}
我要将我的代码放入按钮处理程序中? 还有之前的这个:
carga.progressBar1.Minimum = 0;
carga.progressBar1.Maximum = 100;
Carga 是我的另一种形式,ProgressBar 就在其中。在这种情况下如何使用BackgroundWorker?
您只能从
ProgressChanged
或 RunWorkerCompleted
事件处理程序更新进度条,因为它们与 UI 线程同步。
基本思想是。
Thread.Sleep
只是模拟这里的一些工作。将其替换为您真实的路由调用。
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
我知道这有点老了,但如果另一个初学者正在经历这个,我将分享一些涵盖更多基本操作的代码,这是另一个示例,其中还包括取消该过程的选项以及向用户报告进程的状态。我将在上面的解决方案中添加 Alex Aza 给出的代码
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
private BackgroundWorker worker;
public MainWindow()
{
InitializeComponent();
InitializeBackgroundWorker();
}
private void InitializeBackgroundWorker()
{
worker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
worker.DoWork += Worker_DoWork;
worker.ProgressChanged += Worker_ProgressChanged;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Simulate a time-consuming operation
for (int i = 1; i <= 100; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
// Do the actual work here
Thread.Sleep(100);
// Report progress to UI thread
worker.ReportProgress(i);
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("Operation was canceled.", "Canceled", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (e.Error != null)
{
MessageBox.Show("Error occurred: " + e.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
MessageBox.Show("Operation completed successfully.", "Completed", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
if (!worker.IsBusy)
{
// Start the background worker
worker.RunWorkerAsync();
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
worker.CancelAsync();
}