Reputation: 479
I have a button and a label on my UI. When i clicks on the button i want to show "In Progress" on the label until the for loop finished and then again the same label should show the result of the collection.
private void button1_Click(object sender, RoutedEventArgs e)
{
label1.Content = "In progress..";
List<string> intList = new List<string>();
for (long i = 0; i <= 50000000; i++)
{
intList.Add("Test");
}
label1.Content = intList.ToString();
}
Upvotes: 0
Views: 443
Reputation: 64068
You'll need to farm the work out to a background thread, otherwise your loop continues on the UI thread hence you see no "progress".
You can use a BackgroundWorker or a Task to accomplish this:
private void button1_Click(object sender, RoutedEventArgs e)
{
label1.Content = "In progress..";
Task.Factory.StartNew<List<string>>(
() =>
{
List<string> intList = new List<string>();
for (long i = 0; i <= 50000000; i++)
{
intList.Add("Test");
}
return intList;
})
.ContinueWith(
(t) => label1.Content = t.Result.ToString(),
TaskScheduler.FromCurrentSynchronizationContext());
}
Upvotes: 2
Reputation: 103
You should do that with BackgroundWorker. Here it seems nice example of how to do that. http://elegantcode.com/2009/07/03/wpf-multithreading-using-the-backgroundworker-and-reporting-the-progress-to-the-ui/
Upvotes: 0
Reputation: 1827
Use a background worker to do your actual work (the for loop) and subscribe to the event he raises when his function completes. You can also check progress etc for a more valuable progress meter.
Upvotes: 0