c# – How do I update the text in a Label with a specific frequency?

Question:

How to update the text in the Label with a certain frequency (1 sec. For example) ?. tried this code:

     for (; ; )
        {
            Task.Delay(1000);
            countDownLabel.Content =
                String.Format(/*подстановка обновляемого текста*/);
        }

but the window freezes. How to fix the problem?

Answer:

It hangs because you are not expecting a task: the Task.Delay method returns control immediately, and so you. heavily load the UI with redrawing. It is more correct like this:

for (; ; )
{
    await Task.Delay(1000);
    countDownLabel.Content = String.Format(/*подстановка обновляемого текста*/);
}

You may want to be able to stop the update:

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 are not very familiar with async / await, you can use a timer . Don't forget about Control.Invoke for accessing interface elements.

timer = new Timer(UpdateLabel, null, 1000, 1000);
...
private void UpdateLabel()
{
    if (countDownLabel.InvokeRequired)
    {
        countDownLabel.Invoke(UpdateLabel);
    }
    else
    {
        countDownLabel.Content = String.Format(/*подстановка обновляемого текста*/);
    }
}
...
timer.Dispose();
Scroll to Top