- Add using
using System.ComponentModel;
- Declare Background Worker:
private readonly BackgroundWorker worker = new BackgroundWorker();
- Subscribe to events:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
- Implement two methods:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
- Run worker async whenever your need.
worker.RunWorkerAsync();
-
Track progress (optional, but often useful)
a) subscribe to
ProgressChanged
event and useReportProgress(Int32)
inDoWork
b) set
worker.WorkerReportsProgress = true;
(credits to @zagy)