user1399377
user1399377

Reputation: 479

Show in progress label until the operation finished

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

Answers (3)

user7116
user7116

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

Lashas
Lashas

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

steveg89
steveg89

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

Related Questions