This code is from my C# WPF application:
public MainWindow()
{
InitializeComponent();
status("Getting dl links");
getLinks();
}
The procedure getLinks currently displays a couple of links in a messagebox. Those links are displayed in a messagebox before the WPF application becomes visible.
In this is case not a problem, but how would I show progress (like a progressbar) of any
procedure I want to load at startup?
Here is an example on how you can do it. To simplify it a bit, I added the controls directly in the
MainWindowconstructor, but I would prefer to do this with XAML.I first add a
ProgressBarsomewhere on the interface to make it visible for this demo and then I add it to a newStackPanel, it could be any panel at all, in this case it doesn’t matter.To load the links on another thread, I create a new
Task, this is a part of theTPL(Task Parallel Library) in .NET 4.0. In this case I am simulating thatgetLinks()takes 5 * 500 milliseconds to run and that it in fact is five links that will be loaded, hence 20% each iteration.What I do then is that I add
20to theprogressBarvalue, which indicates that it increased with 20%.This line might confuse you a bit
Dispatcher.Invoke(new Action(() => { progressBar.Value += 20; }));But it is in fact quite common when you do cross-thread programming with GUI. So the problem is that you are on another thread here, we started of a
Taskthat will run on a separate thread, and you cannot update your UI thread from another thread. So what you need is something called aDispatcher, and this is accessable from within yourWindow-class.Then you
Invokean action on it, which means that you simply say “Run this piece of code on this thread for me”.And if you want to display a
MessageBoxwhen everything is loaded, you can simply add aMessageBox.Show("Loaded!");after thefor-loop.