How to proper implement await async in c#
本问题已经有最佳答案,请猛点这里访问。
我是新来的C和我正在尝试使用C中的Async和Wait函数来处理线程和非阻塞GUI。
这就是我目前为止所拥有的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public async Task ReadInfo() { string serial; android.UpdateDeviceList(); if (android.HasConnectedDevices) { serial = android.ConnectedDevices[0]; device = android.GetConnectedDevice(serial); string model = device.BuildProp.GetProp("ro.product.model"); string bootloader = device.BuildProp.GetProp("ro.bootloader"); string pda = device.BuildProp.GetProp("ro.build.PDA"); addlog("Model :" , Color.White, true, true); addlog(model, Color.DodgerBlue, true, false); addlog("Bootloader :", Color.White, true, true); addlog(bootloader, Color.DodgerBlue, true, false); addlog("PDA Version :", Color.White, true, true); addlog(pda, Color.DodgerBlue, true, false); } else { addlog("ADB device not found.", Color.Red, true, true); } } |
这是addlog方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public void addlog(string s, Color color, bool isBold, bool newline = false) { if (newline) { rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.AppendText(" "))); } Color selectionColor = color; rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionStart = rtbLog.Text.Length)); rtbLog.BeginInvoke(new MethodInvoker(() => selectionColor = rtbLog.SelectionColor)); rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionColor = color)); if (isBold) { rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionFont = new Font(rtbLog.Font, FontStyle.Bold))); } rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.AppendText(s))); rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionColor = selectionColor)); rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionFont = new Font(rtbLog.Font, FontStyle.Regular))); rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.ScrollToCaret())); } |
在按钮1上单击"我有:
1 2 3 4 | private async void Button1_Click(object sender, EventArgs e) { await ReadInfo(); } |
我不知道为什么它会冻结图形用户界面。
Solution to the problem
改变
1 | public async Task ReadInfo() |
到
1 | public void ReadInfo() |
并调用按钮1单击为
1 | Task.Run(() => ReadInfo()); |
添加