这里是完整且可用的代码。
C#(Windows类)
public partial class ForceSyncWindow : Window
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
public ForceSyncWindow()
{
InitializeComponent();
ProgressBar1.Visibility = System.Windows.Visibility.Hidden;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
ProgressBar1.Value = 0;
}
else
{
}
ProgressBar1.Value = 0;
ProgressBar1.Visibility = System.Windows.Visibility.Hidden;
this.Synchronize.IsEnabled = true;
this.Cancel.IsEnabled = false;
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
if (backgroundWorker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
backgroundWorker.ReportProgress(i);
System.Threading.Thread.Sleep(100); ;
}
}
}
void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar1.Value = e.ProgressPercentage;
}
private void Synchronize_Click(object sender, RoutedEventArgs e)
{
ProgressBar1.Value = 0;
ProgressBar1.Visibility = System.Windows.Visibility.Visible;
this.Synchronize.IsEnabled = false;
this.Cancel.IsEnabled = true;
backgroundWorker.RunWorkerAsync();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
}
}
}
XAML
<Window x:Class="MySyncManager.Views.ForceSyncWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ForceSyncWindow" Height="300" Width="509" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Grid>
<Button Content="Synchronize" Name="Synchronize" HorizontalAlignment="Left" Margin="411,10,0,0" VerticalAlignment="Top" Width="75" Click="Synchronize_Click"/>
<RichTextBox HorizontalAlignment="Left" Height="132" Margin="10,116,0,0" VerticalAlignment="Top" Width="476">
</RichTextBox>
<Button Content="Cancel" x:Name="Cancel" HorizontalAlignment="Left" Margin="411,40,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.508,2.154" Click="Cancel_Click"/>
<ProgressBar Name="ProgressBar1" HorizontalAlignment="Left" Height="10" Margin="10,101,0,0" VerticalAlignment="Top" Width="476"/>
</Grid>
</Window>