Condividi tramite


BackgroundWorker Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Runs an operation on a separate thread.

Inheritance Hierarchy

System.Object
  System.ComponentModel.BackgroundWorker

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)

Syntax

'Declaration
Public Class BackgroundWorker
public class BackgroundWorker

The BackgroundWorker type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 BackgroundWorker Initializes a new instance of the BackgroundWorker class.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 CancellationPending Gets a value that indicates whether the application has requested cancellation of a background operation.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 IsBusy Gets a value that indicates whether the BackgroundWorker is running a background operation.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 WorkerReportsProgress Gets or sets a value that indicates whether the BackgroundWorker can report progress updates.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 WorkerSupportsCancellation Gets or sets a value that indicates whether the BackgroundWorker supports asynchronous cancellation.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 CancelAsync Requests cancellation of a pending background operation.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 OnDoWork Raises the DoWork event.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 OnProgressChanged Raises the ProgressChanged event.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 OnRunWorkerCompleted Raises the RunWorkerCompleted event.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ReportProgress(Int32) Raises the ProgressChanged event.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ReportProgress(Int32, Object) Raises the ProgressChanged event.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 RunWorkerAsync() Starts running a background operation.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 RunWorkerAsync(Object) Starts running a background operation and includes a parameter for use by the background operation.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Events

  Name Description
Public eventSupported by Silverlight for Windows PhoneSupported by Xbox 360 DoWork Occurs when RunWorkerAsync is called.
Public eventSupported by Silverlight for Windows PhoneSupported by Xbox 360 ProgressChanged Occurs when ReportProgress is called.
Public eventSupported by Silverlight for Windows PhoneSupported by Xbox 360 RunWorkerCompleted Occurs when the background operation has completed, has been canceled, or has raised an exception.

Top

Remarks

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations, such as downloads and database transactions, can cause your user interface to stop responding. When you want a responsive user interface and you must perform time-consuming operations, the BackgroundWorker class provides a convenient solution.

To run an operation in the background, create a BackgroundWorker. You can listen for events that report the progress of your operation and signal when your operation is completed.

To set up a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the background operation, call the RunWorkerAsync method. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

NoteNote:

You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

If your background operation requires a parameter, call RunWorkerAsync with your parameter. Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs.Argument property.

For more information about BackgroundWorker, see How to: Use a Background Worker.

Examples

The following code example demonstrates the use of the BackgroundWorker class for running a time-consuming operation asynchronously. The time-consuming operation is simulated by calling the background thread's Sleep method. The example periodically reports progress and permits the operation to be canceled.

Imports System.ComponentModel

Partial Public Class Page
    Inherits UserControl
    Private bw As BackgroundWorker = New BackgroundWorker

    Public Sub New()
        InitializeComponent()

        bw.WorkerReportsProgress = True
        bw.WorkerSupportsCancellation = True
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

    End Sub
    Private Sub buttonStart_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If Not bw.IsBusy = True Then
            bw.RunWorkerAsync()
        End If
    End Sub
    Private Sub buttonCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If bw.WorkerSupportsCancellation = True Then
            bw.CancelAsync()
        End If
    End Sub
    Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        For i = 1 To 10
            If bw.CancellationPending = True Then
                e.Cancel = True
                Exit For
            Else
                ' Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(500)
                bw.ReportProgress(i * 10)
            End If
        Next
    End Sub
    Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        If e.Cancelled = True Then
            Me.tbProgress.Text = "Canceled!"
        ElseIf e.Error IsNot Nothing Then
            Me.tbProgress.Text = "Error: " & e.Error.Message
        Else
            Me.tbProgress.Text = "Done!"
        End If
    End Sub
    Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
        Me.tbProgress.Text = e.ProgressPercentage.ToString() & "%"
    End Sub
End Class
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SL_BackgroundWorker_CS
{
    public partial class Page : UserControl
    {
        private BackgroundWorker bw = new BackgroundWorker();

        public Page()
        {
            InitializeComponent();

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }
        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress((i * 10));
                }
            }
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.tbProgress.Text = "Canceled!";
            }

            else if (!(e.Error == null))
            {
                this.tbProgress.Text = ("Error: " + e.Error.Message);
            }

            else
            {
                this.tbProgress.Text = "Done!";
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}
<UserControl x:Class="SL_BackgroundWorker_CS.Page"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Height="30" Orientation="Horizontal" 
                    HorizontalAlignment="Left" VerticalAlignment="Top" 
                    Margin="10" >
            <Button x:Name="buttonStart" Content="Start" Click="buttonStart_Click"
                    Width="80" Height="30"/>
            <Button x:Name="buttonCancel" Content="Cancel" Click="buttonCancel_Click"
                    Width="80" Height="30"/>
        </StackPanel>
        <StackPanel Margin="10,50,0,0" Orientation="Horizontal">
            <TextBlock Text="Progress: "/>
            <TextBlock x:Name="tbProgress"/>
        </StackPanel>
    </Grid>
</UserControl>
<UserControl x:Class="SL_BackgroundWorker_VB.Page"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Height="30" Orientation="Horizontal" 
                    HorizontalAlignment="Left" VerticalAlignment="Top" 
                    Margin="10" >
            <Button x:Name="buttonStart" Content="Start" Click="buttonStart_Click"
                    Width="80" Height="30"/>
            <Button x:Name="buttonCancel" Content="Cancel" Click="buttonCancel_Click"
                    Width="80" Height="30"/>
        </StackPanel>
        <StackPanel Margin="10,50,0,0" Orientation="Horizontal">
            <TextBlock Text="Progress: " />
            <TextBlock x:Name="tbProgress" />
        </StackPanel>
    </Grid>
</UserControl>

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.