How to time ListBox load time WPF

2019-09-05 05:45发布

问题:

I'm playing around with DataVirtualization and Async. What are some options I have for quantifying load times of a ListBox that I'm binding my virtualized data collections to?

I need a way to compare the virtualized vs non-virtualized data loading. Have been unsuccessful in locating any resources for this topic.

Should I just put a stopwatch on the ListBox_Loaded event in the code behind?

Thanks in advance!

回答1:

You can use a System.Diagnostics.Stopwatch for this. Make sure that you start it before you set the ListBox.ItemsSource property and stop it as you said, in the ListBox.Loaded event:

In XAML:

<ListBox Name="ListBox" />

In code constructor:

public MainWindow()
{
    InitializeComponent();
    ListBox.Loaded += new RoutedEventHandler(ListBox_Loaded);
    Items.AddRange(Enumerable.Range(1, 100000000));
    stopwatch = new Stopwatch();
    stopwatch.Start();
    ListBox.ItemsSource = Items;
}

Add the handler with a break point after the call to stop the Stopwatch:

private void ListBox_Loaded(object sender, RoutedEventArgs e)
{
    stopwatch.Stop();
    TimeSpan elapsedTime = stopwatch.Elapsed;
}

However, unless you have millions of rows of data, or extremely complicated DataTemplates, you may not see much differences. In this simple example, these 100,000,000 numbers are processed in well under one second. Even when I added a larger DataTemplate for the integers, it still rendered them all in just over one second. Furthermore, repeatedly running this scenario will return differing results, so this is somewhat unreliable as well.