The first thing to understand here is that you should perform the New/Edit/Delete operations on a background thread in order to keep your UI responsive and for the ProgressBar
to be able to update during the time it takes for these operations to complete.
The preferred and easiest way to off-load some work to a background thread is to use the task parallel library (TPL) and start a new task. Keep in mind that WPF controls have thread affinity though so you can only access them on the thread on which they were originally created and that is the dispatcher thread.
So you could implement this by setting the Visibility
property of the ProgressBar
to Visible
, start a task that performs the actual New/Edit/Delete operation and then set the Visibility
property back to Collapsed
again once the task has finished:
C#:
pb.Visibility = Visibility.Visible;
Task.Run(()=>
{
//perform your long-running operation here...make sure that you don't access any UI elements
Save();
})
.ContinueWith(task =>
{
//this delegate will be executed back on the UI thread once the task has finished because of the scheduler returned from the TaskScheduler.FromCurrentSynchronizationContext() method...
pb.Visibility = Visibility.Collapsed;
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
XAML:
<ProgressBar x:Name="pb" IsIndeterminate="True" Visibility="Collapsed" />