private void Button_Click_2(object sender, RoutedEventArgs e)
{
// Start a stop watch to count the execution time
var stopWatch = Stopwatch.StartNew();
lstItems.Items.Clear();
// Define and start a new thread to add 20000 items to the list box
ThreadStart job = new ThreadStart(() =>
{
for (int i = 0; i < 20000; i++)
{
// The new thread puts UI operations in the dispatching queue
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
lstItems.Items.Add("Stock Item " + i);
}));
}
stopWatch.Stop();
//! I cannot access WPF objects that is on the UI thread like this:
// lblTime.Content = "Finished in " + (double)stopWatch.ElapsedMilliseconds / 1000 + " seconds";
// I have to use the Dispatcher class as a mediator to queue the UI operation
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
lblTime.Content = "Finished in " + (double)stopWatch.ElapsedMilliseconds / 1000 + " seconds";
}));
});
Thread thread = new Thread(job);
thread.Start();
}
No comments:
Post a Comment