Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

BackgroundWorker Class ใน C#

BackgroundWorker ใช้รันงานหนักใน Background thread ไม่บล็อก UI (Windows Forms) สื่อสารกับ UI thread ผ่าน Events

Properties สำคัญ

Propertyคำอธิบาย
CancellationPendingTrue ถ้ามีการร้องขอยกเลิก (CancelAsync())
IsBusyTrue ถ้ากำลังรัน Async operation
WorkerReportsProgressTrue = รองรับ ReportProgress()
WorkerSupportsCancellationTrue = รองรับ CancelAsync()

Events สำคัญ

  • DoWork - รันใน Background thread (ทำงานหนักที่นี่)
  • ProgressChanged - รันใน UI thread (เมื่อเรียก ReportProgress)
  • RunWorkerCompleted - รันใน UI thread (เมื่อเสร็จ หรือ Cancel หรือ Error)

ตัวอย่างการใช้งาน

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;

worker.DoWork += (sender, e) => {
    for (int i = 0; i <= 100; i++) {
        if (worker.CancellationPending) { e.Cancel = true; break; }
        // งานหนัก...
        worker.ReportProgress(i);
        Thread.Sleep(50);
    }
};

worker.ProgressChanged += (sender, e) => {
    progressBar.Value = e.ProgressPercentage;
    lblStatus.Text = $"Processing... {e.ProgressPercentage}%";
};

worker.RunWorkerCompleted += (sender, e) => {
    if (e.Cancelled) lblStatus.Text = "Cancelled";
    else if (e.Error != null) lblStatus.Text = "Error: " + e.Error.Message;
    else lblStatus.Text = "Completed!";
};

worker.RunWorkerAsync(); // เริ่มต้น
// ยกเลิก: worker.CancelAsync();

หมายเหตุ: สำหรับ .NET ใหม่ ควรใช้ Task.Run + async/await + IProgress<T> แทน ซึ่งทันสมัยและยืดหยุ่นกว่า