代码:
BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent(); bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += bw_RunWorkerCompleted; } void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.txtMsg.Text = "下载完成";
} void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.mySlider.Value = (double)e.ProgressPercentage / ;
this.txtMsg.Text = ((double)e.ProgressPercentage / ).ToString(); } void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = ; i < ; i++)
{
if (bw.CancellationPending == true)
{
e.Cancel = true;
return;
} bw.ReportProgress(i);
Thread.Sleep(TimeSpan.FromSeconds()); } } private void btnStart_Click(object sender, RoutedEventArgs e)
{
bw.RunWorkerAsync(); } private void btnCancel_Click(object sender, RoutedEventArgs e)
{
bw.CancelAsync();
}