我创建了一个简单的代码示例,您可以使用它来了解后台工作人员的工作方式。将代码复制到测试表单并添加以下控件
- 标签控件 - 将其命名为“lblStatus”
- Progressbar Control - 它应该被命名为progressBar1。
- 添加 2 个名为“btnStartAsyncOperation”和“btnCancel”的按钮并链接它们的点击事件。
基本上你应该在RunWorkerCompleted事件中显示结果
public partial class Form1 : Form
{
BackgroundWorker backgroundWorker;
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker {WorkerReportsProgress = true, WorkerSupportsCancellation = true};
backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
}
void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
lblStatus.Text = "Task Cancelled.";
else if (e.Error != null)
lblStatus.Text = "Error - " + e.Error.Message;
else
lblStatus.Text = "Task Completed...";
btnStartAsyncOperation.Enabled = true;
btnCancel.Enabled = false;
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(100);
backgroundWorker.ReportProgress(i);
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
backgroundWorker.ReportProgress(0);
return;
}
}
backgroundWorker.ReportProgress(100);
}
private void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
btnStartAsyncOperation.Enabled = false;
btnCancel.Enabled = true;
backgroundWorker.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
}
}
}
根据OP的评论编辑
在 DoWork 事件中,将您的字符串设置如下
e.Result = "Your String";
并在 RunWorkerCompleted 事件中
string muResult = Convert.ToString(e.Result);
注意: e.Result 是一个对象,因此您甚至可以在其中设置具有多个属性的自定义类。