我創建了一個簡單的代碼示例,您可以使用它來了解後臺工作程序的工作方式。將代碼複製到測試窗體並添加以下控件
- 標籤控制 - 將它命名爲「lblStatus」
- 進度控制 - 它應該被命名爲progressBar1。
- 添加名爲'btnStartAsyncOperation'和'btnCancel'的2個按鈕和鏈接其點擊事件。
基本上你應該顯示在結果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";
a第二在RunWorkerCompleted事件
string muResult = Convert.ToString(e.Result);
注: e.Result是一個對象,所以你甚至可以用它的多個屬性中設置自定義類。
這不起作用,你需要在UI線程上顯示對話框。獲取表單來處理工作人員的'RunWorkerCompleted'事件,然後顯示對話框。 – dlev 2013-04-20 02:57:02
@dlev,我明白了,但我需要doWork中的值列表來顯示在MessageBox中。有沒有辦法將doWork中的值傳遞給RunWorkerCompleted?謝謝! – SHINHAN 2013-04-20 03:48:34