xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:d='http://schemas.microsoft.com/expression/blend/2008' xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' mc:Ignorable='d' d:DesignWidth='640' d:DesignHeight='480'> Grid.Row="0" Orientation="Vertical"> Width="200" Height="20" /> Width="200" Height="20" /> Grid.Row="1" Orientation="Horizontal"> Width="100" Height="20" Content="Start Task" Click="btnStartTask_Click" /> Width="100" Height="20" Content="Cancel Task" Click="btnCancelTask_Click" /> //File: Page.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.ComponentModel; namespace SilverlightApplication3 { public partial class MainPage : UserControl { private BackgroundWorker backgroundWorker = new BackgroundWorker(); public MainPage() { InitializeComponent(); backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.WorkerSupportsCancellation = true; backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged); backgroundWorker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted); } void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { txtPercentComplete.Text = e.Error.Message; } else if (e.Cancelled) { txtPercentComplete.Text = "Task Cancelled"; } else { txtPercentComplete.Text = "Task Completed"; } } void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { txtPercentComplete.Text = e.ProgressPercentage.ToString() + " %"; } void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { const int SECOND = 1000; BackgroundWorker backgroundWorker = (BackgroundWorker)sender; for (int i = 0; i < 20; i++) { if (backgroundWorker.CancellationPending) { e.Cancel = true; return; } backgroundWorker.ReportProgress((i + 1) * 5); System.Threading.Thread.Sleep(SECOND / 4); } } private void btnStartTask_Click(object sender, RoutedEventArgs e) { backgroundWorker.RunWorkerAsync(); } private void btnCancelTask_Click(object sender, RoutedEventArgs e) { backgroundWorker.CancelAsync(); } } }