Wh开发者_开发百科at good is an indeterminate progress bar that is frozen because of course its on the same thread? Is there a way to keep it running? Possibly multi-threading?
Threading is almost certainly the solution, yes - or asynchronous operations. You definitely shouldn't be performing a long-running task in the UI thread.
One common pattern is to use BackgroundWorker
for the background task - it makes it particularly easy to report progress back to the UI thread.
The answer was using a separate thread. I didn't realize I could create multiple STA threads. I created a simple delegate thread bubble that I pop whenever I want to hide the progress window.
protected void ShowProgress()
{
if (_progressThread != null)
return;
_progressThread = new Thread(() =>
{
var progressShell = Program.ViewFactory.CreateDialogShell();
progressShell.DataContext = new ProgressViewModel(this);
progressShell.Show();
Dispatcher.Run();
});
_progressThread.SetApartmentState(ApartmentState.STA);
_progressThread.Start();
}
protected void HideProgress()
{
if (_progressThread == null)
return;
_progressThread.Abort();
_progressThread = null;
}
Code I've used in this situation
ProgressIndicator.Visibility = System.Windows.Visibility.Visible;
ThreadPool.QueueUserWorkItem
(
delegate
{
// Perform slow action
Thread.Sleep(5000);
this.Dispatcher.Invoke(
new Action(delegate()
{
// Insert UI related activity here.
// ....
ProgressIndicator.Visibility = System.Windows.Visibility.Collapsed;
}
));
}
);
Not sure about the details of your problem but I had a similar-sounding problem (maybe?) where I had a ListView with many (hundreds) of thumbnails that needed to be displayed. The thumbnails were generated from digital photos on the file-system so creating that many thumbnails would have locked up the UI while they all loaded. I created all of the objects in the ListView with a placeholder image (tiny JPG with the string "Loading..."), and just enough data so that the background worker would then update each object in the ListView with the thumbnail, and possibly other data from the file (the data for the placeholder objects came from a simple database query). The user gets a UI that's responsive while the loading occurs. This worked well because loading the placeholder data for hundreds of objects was quick enough (a few seconds), compared to possibly minutes for very large sets of data. I don't know enough about your situation to know if this would work...
精彩评论