代码
<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>
代码
using System.ComponentModel;
namespace BackgroundWorker
{
public partial class Page : UserControl
{
private System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.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)
{
System.ComponentModel.BackgroundWorker worker = sender as System.ComponentModel.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() + "%");
}
}
}
如果后台操作需要参数,请在调用 RunWorkerAsync 时给出参数。在 DoWork 事件处理程序内部,可以从 DoWorkEventArgs..::..Argument 属性中提取该参数。