C# – Progress Bar using Async Function in WPF
MiniBytes: In this article you are going to see, how to create a progress bar using the C# Async function. This tutorial will be helpful for you to create a progress bar which you can use in your C# Form application or WPF application. But here i am going to narrate a function which you can use in WPF application.
In this tutorial we are going to use a Async function. By using this function you can run a progress bar in your form application or a WPF application. Below is the code which we are going to use in the C#.
private async void runFunction()
var progress = new Progress<int>(value => progressBar.Value = value);
await Task.Run(() =>
for (int i = ; i < 100; i++)
progressBar.Dispatcher.Invoke(() => progressBar.Value = i, System.Windows.Threading.DispatcherPriority.Background);
WPF Property Vaules:
“Name” of the progress bar (in XAML code) : progressBar
“Value” of the progress bar (in XAML code): value
From the above code we can tell that it was going to load the “loadList()” function which is going to have a small code. The code is nothing but a sleep() function which can be used to pause the function every time it was called.
public void loadList()
So whenever we are running the above function, it will pause or sleep for 1 second.
for loop is user here because, for every second the value of the progress bar will be incremented, that displays the change in the display of the progress bar.
Here i have used the dispatcher.Invoke() method here because, instead of allocating a separate thread, same thread will be used to run the function. If this dispatcher.Invoke() was not used, then it will throw an error. You also need to use the the async keyword near public or private because if you are using the await method, then it need to be declared.