Tuesday 30 September 2008

Background Worker Class

When running an operation that takes a long time the UI can freeze, to avoid this you can run the operation in a new Thread. With .NET 2.0 you can use the BackgroundWorker class to do this easily (in Windows Applications).


You can either drag and drop the BackgroundWorker component onto your form or instantiate it through code.


The BackgroundWorker class has 3 events; DoWork, ProgressChanged and RunWorkerCompleted.


Add the code for the operation to be carried out into the DoWork event handler. If the BackgroundWorker is to report progress, handle the ProgressChanged event and add any code to be carried out upon completion of the operation in the RunWorkerCompleted event.
To start the operation call the RunWorkerAsync(); method. The operation can be cancelled by calling the CancelAsync(); method, only if the WorkerSupportsCancellation property is True.

No comments:

Free Hit Counter