I had a bit of a challenge today while trying to get a WPF ProgressBar to send feedback to my UI while a long-running processes ran.
My first challenge was finding “that one property that lets the ProgressBar animation run continuously” – IsIndeterminate.
My next challenge was setting the IsIndeterminate property to true before firing off my long-running process. I remembered something about using the Dispatcher, but even using that didn’t reflect the ProgressBar property changes to the UI. I briefly considered trying an evil DoEvents type trick, but came to my senses before heading down that road.
I landed on creating a delegate which I could invoke to fire off my long-running process, and it ended up looking something like this (forgive the crude method names, this was some spike code I was playing around with:
private delegate void UpdateProgressbarIndeterminateState(bool isEnabled);
private void CompareClick(object sender, RoutedEventArgs e){
Dispatcher.Invoke(DispatcherPriority.Normal,
(UpdateProgressbarIndeterminateState)
delegate(bool isIndeterminate){
progressBar.IsIndeterminate = isIndeterminate;
}, true);
AsyncDelegate caller = PerformCompare;
caller.BeginInvoke(AfterCompareCallback, null);
}
internal delegate void AsyncDelegate();
private static void PerformCompare() {
DataComparer.Execute();
}
protected void AfterCompareCallback(IAsyncResult ar) {
Dispatcher.Invoke(DispatcherPriority.Normal,
(UpdateProgressbarIndeterminateState)
delegate(bool isIndeterminate) {
progressBar.IsIndeterminate = isIndeterminate;
}, false);
}
No comments:
Post a Comment