private BackgroundWorkerbackgroundWorker;
public MainWindow()
{
InitializeComponent();
int mainThreadID =Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("主线程ID:" +mainThreadID);
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress =true;
backgroundWorker.WorkerSupportsCancellation =true;
backgroundWorker.ProgressChanged +=BackgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted +=BackgroundWorker_RunWorkerCompleted;
backgroundWorker.DoWork +=BackgroundWorker_DoWork;
}
voidBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
int backgroundWokrdThreadID =Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("DoWork BackgroundWorker线程ID:"+ backgroundWokrdThreadID);
int count = 0;
//while (true)
while (count<10)
{
if(backgroundWorker.CancellationPending)
return;
count++;
backgroundWorker.ReportProgress(count * 10, string.Format("当前进度:{0}%", count * 10));
Dispatcher.BeginInvoke(new Action(() =>
{
this.showTB.Text =string.Format("当前进度:{0} %", count * 10);
}),
DispatcherPriority.Normal, null);
}
}
voidBackgroundWorker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
int backgroundWokrdThreadID =Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("RunWorkerCompletedBackgroundWorker线程ID:" + backgroundWokrdThreadID);
}
voidBackgroundWorker_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
int backgroundWokrdThreadID =Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("ProgressChangedBackgroundWorker线程ID:" + backgroundWokrdThreadID);
int progressValue = e.ProgressPercentage;
Console.WriteLine(string.Format("当前进度:{0} %",progressValue));
}
private voidStartBackgroundWorker_Click(object sender, RoutedEventArgs e)
{
backgroundWorker.RunWorkerAsync();
}
private voidCancelBackgroundWorker_Click(object sender, RoutedEventArgse)
{
backgroundWorker.CancelAsync();
backgroundWorker.Dispose();
}
<GridBackground="Black">
<ButtonContent="StartBackgroundWorker" HorizontalAlignment="Left"Margin="29,29,0,0" VerticalAlignment="Top" Width="154" Height="33"Click="StartBackgroundWorker_Click"/>
<TextBlock Name="showTB"HorizontalAlignment="Left" Margin="29,82,0,0" TextWrapping="Wrap"Text="" VerticalAlignment="Top" Height="165" Width="391"
Background="OrangeRed" Foreground="White"FontSize="24" FontWeight="Bold"/>
<ButtonContent="CancelBackgroundWorker" HorizontalAlignment="Left"Margin="261,29,0,0" VerticalAlignment="Top" Width="159" Height="33"Click="CancelBackgroundWorker_Click"/>
</Grid>