Last week, a colleague of mine asked me an interesting question: “I’m filling a control with content and I’d like to measure the time needed to render my control. How can I do that ?”
The first approach is to measure the elapsed time needed to instantiate and populate the control from C# code. We can use the StopWatch class to have a precise and easy to use measuring tool.
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 5000; i++)
{
// here is the operation that fills the control
this.canvas.Children.Add(new Rectangle());
}
sw.Stop();
MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");
However this approach will not give good results because we're not taking into account the time needed to render elements in the visual tree. This is because elements are not rendered when you call the Add methods (for example in a Canvas) but when the visual tree is fully loaded.
A much better approach is to use the Dispatcher and request it to process an action at a priority right bellow the Render priority which is the Loaded priority:
Using this trick, we ensure that all rendering actions have been completed. We can use the following code to do that:
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 5000; i++)
{
// here is the operation that fills the control
this.canvas.Children.Add(new Rectangle());
}
this.Dispatcher.BeginInvoke(
DispatcherPriority.Loaded,
new Action(() =>
{
sw.Stop();
MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");
}));
Hope this helps !