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;
- }
- }
Run the application and click Start… You will see our application
Freezes. Look at Task Manager to see
Not Responding status.
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,
-
- private readonly SynchronizationContext synchronizationContext;
- private DateTime previousTime = DateTime.Now;
-
- public Form1()
- {
- InitializeComponent();
- synchronizationContext = SynchronizationContext.Current;
- }
-
-
- 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;
-
-
- if ((DateTime.Now - previousTime).Milliseconds <= 50) return;
-
-
- 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.
Conclusion
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.