当前位置: 欣欣网 > 码农

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"); }

亲测,可以正常工作。