C# 无意间写了一段线程死锁的代码
源码如下:
private void 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); private void 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去做
private void action_Click(object sender, RoutedEventArgs e) { TaskTest(); } public async void TaskTest() { await Task.Run(() => { for (int i = 0; i < 10; i++) { Thread.Sleep(1000); this.Dispatcher.Invoke(() => { lblStr.Content = i.ToString(); }); } }); MessageBox.Show("123"); }
本文来源自公众号【dotnet编程大全】,需要进技术群交流的,请添加小编mm1552923!