Tuesday, February 21, 2017

C# - Prevent "Not Responding" error in Win form by using Task.Run

This function will make your application "Not Responding".

     private void button1_Click(object sender, EventArgs e)  
     {  
       for (int i = 0;i < 100000000; i++)  
       {  
         label1.Text = "i = " + i.ToString();  
       }  
     }  

Modify it a little bit, we can prevent "Not Responding" error happen by using Task.Run method like this:
     private async void button2_Click(object sender, EventArgs e)  
     {  
       await Task.Run(() =>  
       {  
         for (int i = 0; i < 100000000; i++)  
         {  
           label1.Text = "i = " + i.ToString();  
         }  
       });  
     }  

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.