Export (0) Print
Expand All
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

BackgroundWorker Class

July 28, 2014

Runs an operation on a separate thread.

System.Object
  System.ComponentModel.BackgroundWorker

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

public class BackgroundWorker

The BackgroundWorker type exposes the following members.

  NameDescription
Public methodBackgroundWorkerInitializes a new instance of the BackgroundWorker class.
Top

  NameDescription
Public propertyCancellationPendingGets a value that indicates whether the application has requested cancellation of a background operation.
Public propertyIsBusyGets a value that indicates whether the BackgroundWorker is running a background operation.
Public propertyWorkerReportsProgressGets or sets a value that indicates whether the BackgroundWorker can report progress updates.
Public propertyWorkerSupportsCancellationGets or sets a value that indicates whether the BackgroundWorker supports asynchronous cancellation.
Top

  NameDescription
Public methodCancelAsyncRequests cancellation of a pending background operation.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnDoWorkRaises the DoWork event.
Protected methodOnProgressChangedRaises the ProgressChanged event.
Protected methodOnRunWorkerCompletedRaises the RunWorkerCompleted event.
Public methodReportProgress(Int32)Raises the ProgressChanged event.
Public methodReportProgress(Int32, Object)Raises the ProgressChanged event.
Public methodRunWorkerAsync()Starts running a background operation.
Public methodRunWorkerAsync(Object)Starts running a background operation and includes a parameter for use by the background operation.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public eventDoWorkOccurs when RunWorkerAsync is called.
Public eventProgressChangedOccurs when ReportProgress is called.
Public eventRunWorkerCompletedOccurs when the background operation has completed, has been canceled, or has raised an exception.
Top

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 for Windows Phone 8.

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.


using Microsoft.Phone.Controls;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SL_BackgroundWorker_CS
{
    public partial class Page : PhoneApplicationPage
    {
        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() + "%");
        }
    }
}



<phone:PhoneApplicationPage x:Class="SL_BackgroundWorker_CS.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel>
            <StackPanel Orientation="Horizontal" 
                        HorizontalAlignment="Left" VerticalAlignment="Top" 
                        Margin="10" >
                <Button x:Name="buttonStart" Content="Start" Click="buttonStart_Click"
                        Width="200" />
                <Button x:Name="buttonCancel" Content="Cancel" Click="buttonCancel_Click"
                        Width="200" />
            </StackPanel>
            <StackPanel Margin="10,50,0,0" Orientation="Horizontal">
                <TextBlock Text="Progress: " />
                <TextBlock x:Name="tbProgress" />
            </StackPanel>
        </StackPanel>
    </Grid>
</phone:PhoneApplicationPage>


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

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

Show:
© 2014 Microsoft