Home > Net >  Animated number counter c# - Windows Forms
Animated number counter c# - Windows Forms

Time:04-24

I would like to implement an animated number counter in c#. There is a lot of material available for JS - CSS and java , but not much for c#. I tryed the following code:

  for (int i = 0; i<value; i  )
        {
            lblCounterDis.Text = i.ToString();
            i  ;
            Thread.Sleep(5);
        }

Using this script i only freeze the application for some seconds. Should i use some BackgroundWorker? Any more advanced method?

CodePudding user response:

You could use await/async to prevent freezing

private async void button1_Click(object sender, EventArgs e)
{
    await UpdateLabelAsync();
}


private async Task UpdateLabelAsync()
{
    for(int i = 0; i < 1000; i  )
    {
        label1.Text = i.ToString();
        await Task.Delay(100);
    }
}

Please note that I used .net 6 for this example. Not sure if it also works with .net framework.

  • Related