In this specific case it appears that all you're doing is essentially counting to 2000 in a label as fast as you possibly can. This is unlikely to be your actual use case.
If you want to be updating the UI between multiple different asynchronous operations (in which that operation is, for example, just waiting for some period of time) then you can structure your code like so:
private async void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 2000; i++)
{
await Task.Delay(TimeSpan.FromSeconds(1));
labelName.Content = i.ToString();
}
}
If what you're conceptually doing is updating the UI with progress of a long running non-UI operation, then the Progress
class is designed to specifically handle that:
private async void Button_Click(object sender, RoutedEventArgs e)
{
Progress<int> progress = new Progress<int>(
i => labelName.Content = i.ToString());
await Task.Run(() => DoWork(progress));
}
private void DoWork(IProgress<int> progress)
{
for (int i = 0; i < 2000; i++)
{
//Do Stuff
progress.Report(i);
}
}
In general the first option makes sense if you can break up your problem into a group of small asynchronous operations in which the UI is updated between each. The second approach is done if there is a single long non-UI operation that cannot be easily broken up into smaller operations.