Letfar
Letfar

Reputation: 3513

How change the value of the form element by each second?

I have class that extends ProgressBar which should release a simple timer.

    public partial class TimerBar: ProgressBar
    {
        public TimerBar()
        {
            InitializeComponent();
            Value = 100; 
        }
        ...
        public void Start()
        {
            int x = 100/Timer; // procent per second

            for (i = Value; i > 0; i--) {
               Value -= x;
            }
        }
     }

How to set delay for 1 second before Value -= x ? (It should not stop other elements)

Upvotes: 1

Views: 51

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100555

If you want to keep loop in the code (and hence can't use Timer approach suggested in the other answer ) you can use async/await with Task.Delay:

public async void Start()
{
    int x = 100/Timer; // percent per second

    for (i = Value; i > 0; i--) {
       Value -= x;
       await Task.Delay(1000);
    }
}

Upvotes: 1

Lex Webb
Lex Webb

Reputation: 2852

You can use the windorms Timer class to raise an event to call a method every second from within your class. This does not block the thread. You would have to re-write your logic a bit and not use a for loop, but it should be able to provide what you need.

Upvotes: 2

Related Questions