0

I have a problem with the progress bars, I want to run two progress bar like I do in the following code:

namespace probando
{
    public partial class MainWindow : Window
    {

            int sec = 0;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            string stringSec = sec.ToString();

            for (int i = 0; i <= sec; i++)
            {
                masuno(i,sec);
            }

        }

        private void Tiempo_segundos_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            sec = (int) Tiempo_segundos.Value;
        }

        private void masuno(int i, int sec)
        {
           Porcentaje_restante.Maximum = sec;

           Porcentaje_restante.Dispatcher.Invoke(() => Porcentaje_restante.Value = i, DispatcherPriority.Background);

           Thread.Sleep(1000);
        }
    }
}

And I have another progressbar which is indeterminate buy doesn´t work while the first bar is working.

Thank you for your help.

Boas Enkler
  • 12,264
  • 16
  • 69
  • 143

3 Answers3

1

Thread.Sleep pauses the current thread.

From your code i assume you are using this in a windows forms or wpf application , right?

Now there is only a single ui thread. Now when you sleep in the ui thread the whole ui is paused. So you have to put worker code which is not the ui in a background thread.

See alsp this question: How to update the GUI from another thread in C#? or How to update UI from another thread running in another class

and this MSDN Article about the Threading Model

Community
  • 1
  • 1
Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
0

If Sleep is used to delay something in UI thread (to simulate work, to split something, whatever), then you can use async/await to do that properly (Sleep is blocking UI thread):

async void masuno(int i, int sec)
{
    ...

    // Thread.Sleep(1000); - instead of this do:
    await Task.Delay(1000);
}
Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • If i do this, the program doesn´t wait every second to update, it makes all together. I don´t know why... – davidtxu74 Mar 31 '16 at 10:37
0

Have a look at the BackgroundWorker which is designed for this kind of scenario. It runs your long process on a background thread and lets you perform UI updates as the progress changes.

Alsty
  • 817
  • 10
  • 23