當前位置: 妍妍網 > 碼農

C# 無意間寫了一段執行緒死結的程式碼

2024-02-09碼農

源碼如下:

privatevoid action_Click(object sender, RoutedEventArgs e) { Task t = new Task(() => {for (int i = 0; i < 10; i++) { Thread.Sleep(1000);this.Dispatcher.Invoke(() => { lblStr.Content = i.ToString(); }); manualResetEvent.Set(); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); } }); t.Start(); t.Wait(); MessageBox.Show("123"); }

正常遮蔽掉t.Wait();時,點選按鈕,界面label會顯示1到9,間隔1秒,

但是加上 t.Wait();直接就卡這裏了。

修改為用ManualResetEvent等待,也是一樣的效果

ManualResetEvent manualResetEvent = new ManualResetEvent(false);privatevoid action_Click(object sender, RoutedEventArgs e) { Task t = new Task(() => {for (int i = 0; i < 10; i++) { Thread.Sleep(1000);this.Dispatcher.Invoke(() => { lblStr.Content = i.ToString(); }); manualResetEvent.Set(); } }); t.Start();//t.Wait(); manualResetEvent.WaitOne(); MessageBox.Show("123"); }

然後在群裏請教了幾位大佬,大佬說是死結了,指導用async和await去做

privatevoidaction_Click(object sender, RoutedEventArgs e) { TaskTest(); }publicasyncvoidTaskTest() {await Task.Run(() => {for (int i = 0; i < 10; i++) { Thread.Sleep(1000);this.Dispatcher.Invoke(() => { lblStr.Content = i.ToString(); }); } }); MessageBox.Show("123"); }

親測,可以正常工作。