1

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)

Letfar
  • 3,253
  • 6
  • 25
  • 35

2 Answers2

2

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.

Lex Webb
  • 2,772
  • 2
  • 21
  • 36
  • To expand a bit: the `Timer` class provides a `Tick` event. You set the timer for 1 second intervals, and on each `Tick`, update your UI. Beware of the need to [Invoke](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke(v=vs.110).aspx) if threading gets involved, as others are suggesting. – DonBoitnott Sep 23 '15 at 15:04
  • 2
    @DonBoitnott note that you are comment is about *different* timer class - WinForms's one *does not* need `Invoke` as it runs on UI thread. – Alexei Levenkov Sep 23 '15 at 15:06
  • @AlexeiLevenkov ..."if threading gets involved". I think I covered that. – DonBoitnott Sep 23 '15 at 15:08
  • @DonBoitnott That quote is a very far cry from the actual situation, which is, "if you use the wrong timer". – Servy Sep 23 '15 at 15:12
1

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);
    }
}
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179