This example can be used in Get records from DB, or to call a long running task and more.
Create our Windows Form
Create a Simple Windows Forms Application in Visual Studio.


Now put a click event at button, and write the following code,
- private void button1_Click(object sender, EventArgs e)
- {
- for (var i = 0; i <= 1000000; i++)
- {
- label1.Text = @"Count : " + i;
- }
- }

How can we get around this
Let’s put another button in our form and add a click event.

At click event method, write the following code,
- //attributes used to refresh UI
- private readonly SynchronizationContext synchronizationContext;
- private DateTime previousTime = DateTime.Now;
- public Form1()
- {
- InitializeComponent();
- synchronizationContext = SynchronizationContext.Current; //context from UI thread
- }
- private async void button2_Click(object sender, EventArgs e)
- {
- button1.Enabled = false;
- button2.Enabled = false;
- var count = 0;
- await Task.Run(() =>
- {
- for (var i = 0; i <= 1000000; i++)
- {
- UpdateUI(i);
- count = i;
- }
- });
- label1.Text = @"Count : " + count;
- button1.Enabled = true;
- button1.Enabled = false;
- }
- public void UpdateUI(int value)
- {
- var timeNow = DateTime.Now;
- //Here we only refresh our UI each 50 ms
- if ((DateTime.Now - previousTime).Milliseconds <= 50) return;
- //Send the update to our UI thread
- synchronizationContext.Post(new SendOrPostCallback(o =>
- {
- label1.Text = @"Count : " + (int)o;
- }), value);
- previousTime = timeNow;
- }
I placed the word ASYNC at click event method to avoid our UI to freeze. At our event look to TASK that make our count. Inside it you will see the method UpdateUI, that refresh the label 50ms each.
Run the application and see the result.
The code is available at https://github.com/mfandre/NonFreezingApp
I hope with this tutorial you learned a little about how we can avoid Freezes at our Desktop Applications. You can use the target idea from this tutorial to improve scenarios like Db Queries, a long running task, read an external file and much more.


Maathangi BaskaranPosted Dec 22, 2021, 6:31 AM EST
Very use full. Thanks a lot
Santhakumar MunuswamyPosted Dec 25, 2015, 9:14 PM EST
Thanks for nice article
Sibeesh VenuTOP 100Posted Dec 21, 2015, 7:09 PM EST
Nice Share
Raja TPosted Dec 21, 2015, 4:41 AM EST
Nice, Thanks for sharing
Gowtham KTOP 100Posted Dec 12, 2015, 1:41 AM EST
Good One, Thanks for sharing
Harshad PansuriyaPosted Dec 11, 2015, 7:56 PM EST
Nice one
Manas MohapatraPosted Dec 11, 2015, 7:54 PM EST
Goo one ..
Ankur MistryTOP 100Posted Dec 11, 2015, 8:19 AM EST
nice share