private BackgroundWorker
backgroundWorker;
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;
}
void
BackgroundWorker_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);
}
}
void
BackgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
int backgroundWokrdThreadID =
Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("RunWorker
CompletedBackgroundWorker线程ID:" + backgroundWokrdThreadID);
}
void
BackgroundWorker_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
int backgroundWokrdThreadID =
Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("ProgressChanged
BackgroundWorker线程ID:" + backgroundWokrdThreadID);
int progressValue = e.ProgressPercentage;
Console.WriteLine(string.Format("当前进度:{0} %",
progressValue));
}
private void
StartBackgroundWorker_Click(object sender, RoutedEventArgs e)
{
backgroundWorker.RunWorkerAsync();
}
private void
CancelBackgroundWorker_Click(object sender, RoutedEventArgs
e)
{
backgroundWorker.CancelAsync();
backgroundWorker.Dispose();
}
<Grid
Background="Black">
<Button
Content="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"/>
<Button
Content="CancelBackgroundWorker" HorizontalAlignment="Left"
Margin="261,29,0,0" VerticalAlignment="Top" Width="159" Height="33"
Click="CancelBackgroundWorker_Click"/>
</Grid>