WinForm layout
using System.Threading
namespace BackgroundWorkerSimple
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
}
private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
lblResult.Text = "取消";
else if (e.Error != null)
lblResult.Text = "錯誤訊息: " + e.Error.Message;
else
lblResult.Text = "完成";
}
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblResult.Text = $"已完成進度:{e.ProgressPercentage}%";
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
// Perform a time consuming operation and report progress.
Thread.Sleep(500);
worker.ReportProgress(i * 10);
}
}
private void btnStartAsync_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy == true) return;
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
private void btnCancelAsync_Click(object sender, EventArgs e)
{
// WorkerSupportsCancellation 屬性為 true,才可以執行 CancelAsync method
if (backgroundWorker1.WorkerSupportsCancellation == false) return;
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
}
}
執行結果
沒有留言:
張貼留言