Updated: September 2010
Executes an operation on a separate thread.
Assembly: System (in System.dll)
The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
The class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the class provides a convenient solution.
To execute a time-consuming operation in the background, create a and listen for events that report the progress of your operation and signal when your operation is finished. You can create the programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.
To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
For more information about , see How to: Run an Operation in the Background.
The following code example demonstrates the basics of the class for executing a time-consuming operation asynchronously.
To try this code, create a Windows Forms application. Add a Label control named resultLabel and add two Button controls named startAsyncButton and cancelAsyncButton. Create Click event handlers for both buttons. From the Components tab of the Toolbox, add a component named backgroundWorker1. Create DoWork, ProgressChanged, and RunWorkerCompleted event handlers for the . In the code for the form, replace the existing code with the following code.
The following code example demonstrates the use of the class for executing a time-consuming operation asynchronously. The operation computes the selected Fibonacci number, reports progress updates as the calculation proceeds, and permits a pending calculation to be canceled.
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98