案例3

 1 public partial class Form1 : Form
 2     {
 3         public Form1()
 4         {
 5             InitializeComponent();
 6         }
 7 
 8         private void Form1_Load(object sender, EventArgs e)
 9         {
10 
11         }
12 
13         private void button1_Click(object sender, EventArgs e)
14         {
18             int result =  HeavyJob();
19             this.label1.Text = result.ToString();21         }
22 
23         int HeavyJob()
24         {
//模拟耗时操作,使用的是同步方式,阻塞了,所以导致界面卡顿
25 Thread.Sleep(2000); 26 return 12; 27 } 28 }
点击界面的button按钮,界面卡顿,知道2s后恢复

解决方式:使用异步

 1  public partial class Form1 : Form
 2     {
 3         public Form1()
 4         {
 5             InitializeComponent();
 6         }
 7 
 8         private void Form1_Load(object sender, EventArgs e)
 9         {
10 
11         }
12 
13         private async  void button1_Click(object sender, EventArgs e)
14         {
15             Console.WriteLine("当前线程:"+ Environment.CurrentManagedThreadId.ToString());
16             //ConfigureAwait(true) 任务结束后还回到原来的线程 ConfigureAwait(false) 不回到原来的线程 
//如果ConfigureAwait(false) 那么将会报错,System.InvalidOperationException:“线程间操作无效: 从不是创建控件“label1”的线程访问它
//因为等待结束后,线程没有回归到ui线程,非ui线程调用ui将会出错
17 int result = await HeavyJob().ConfigureAwait(true); 18 //int result = HeavyJob().Result; 19 this.label1.Text = result.ToString(); 20 Console.WriteLine("当前线程:" + Environment.CurrentManagedThreadId.ToString()); 21 } 22 23 async Task<int> HeavyJob() 24 { 25 await Task.Delay(6000); 26 return 12; 27 } 28 }

 

posted @ 2024-07-14 14:27  NoTimeFF  阅读(28)  评论(0)    收藏  举报