You can use BackgroundWorker for such requirements. Below is a sample that updates a label status based on percentage task [long running] completion
. In addition, there is an example business class that sets some value, and the value is returned to the user interface through the ProgressChanged
handler. DoWork
is the place where you write your long task. Copy. Paste the code below by adding a shortcut and backgroundworker to the Winforms application and take a picture. You can debug various handlers [RunWorkerCompleted, ProgressChanged, DoWork]
and look at the InitWorker
method. Also pay attention to the cancellation feature
.
using System.ComponentModel; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form3 : Form { private BackgroundWorker _worker; BusinessClass _biz = new BusinessClass(); public Form3() { InitializeComponent(); InitWorker(); } private void InitWorker() { if (_worker != null) { _worker.Dispose(); } _worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _worker.DoWork += DoWork; _worker.RunWorkerCompleted += RunWorkerCompleted; _worker.ProgressChanged += ProgressChanged; _worker.RunWorkerAsync(); } void DoWork(object sender, DoWorkEventArgs e) { int highestPercentageReached = 0; if (_worker.CancellationPending) { e.Cancel = true; } else { double i = 0.0d; int junk = 0; for (i = 0; i <= 199990000; i++) { int result = _biz.MyFunction(junk); junk++;
source share