How to update the Label`e with a certain frequency?
-
How did Label`e update the text with a certain frequency(1 sec, e.g.) test the code:
for (; ; ) { Task.Delay(1000); countDownLabel.Content = String.Format(/*подстановка обновляемого текста*/); }
but the window is hanging. How do we solve the problem?
-
Visnet, because you're not expecting a disk: a method.
Task.Delay
He returns the control immediately, and you're putting the UI into a refill. The correct one is:for (; ; ) { await Task.Delay(1000); countDownLabel.Content = String.Format(/*подстановка обновляемого текста*/); }
Maybe you'll want to be able to stop updating:
private async Task UpdateLabel(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { await Task.Delay(1000); countDownLabel.Content = String.Format(/*подстановка обновляемого текста*/); } }
private void Do()
{
// обновляем лейбл в течение 10 секунд
var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
UpdateLabel(tokenSource.Token);
}
If you're not very familiar with async/await, you can use it. https://msdn.microsoft.com/ru-ru/library/system.threading.timer(v=vs.110).aspx ♪ Don't forget. https://msdn.microsoft.com/ru-ru/library/zyzhdc6b(v=vs.110).aspx to access the interface.
timer = new Timer(UpdateLabel, null, 1000, 1000);
...
private void UpdateLabel()
{
if (countDownLabel.InvokeRequired)
{
countDownLabel.Invoke(UpdateLabel);
}
else
{
countDownLabel.Content = String.Format(/подстановка обновляемого текста/);
}
}
...
timer.Dispose();