【发布时间】:2018-01-13 04:13:22
【问题描述】:
我有一个使用 API 数据的表单。从服务器获取数据时,表单被阻止。我尝试使用异步等待和任务,但它没有帮助。无论如何,表格被阻止了。你能解释一下我如何在我的应用程序中应用异步等待吗?
我使用的代码:
private void navigationTreeView_AfterSelect(object sender, TreeViewEventArgs e)
{
Task task = SwitchToProjectsPanelAsync();
task.Wait();
}
private async Task SwitchToProjectsPanelAsync()
{
CurrentPanel.Visible = false;
if (MyAllProjectsFlowLayoutPanel == null)
{
MyAllProjectsFlowLayoutPanel = new MyAllProjectsFlowLayoutPanel(this);
MyAllProjectsFlowLayoutPanel.SuspendLayout();
this.Controls.Add(MyAllProjectsFlowLayoutPanel);
MyAllProjectsFlowLayoutPanel.AllProjects = _controller.GetProjectsList();
MyAllProjectsFlowLayoutPanel.ShowProjectsList();
CurrentPanel = MyAllProjectsFlowLayoutPanel;
CurrentPanel.Visible = true;
MyAllProjectsFlowLayoutPanel.ResumeLayout(false);
MyAllProjectsFlowLayoutPanel.PerformLayout();
}
else
{
CurrentPanel = MyAllProjectsFlowLayoutPanel;
CurrentPanel.Visible = true;
}
}
完整代码在 Git https://github.com/ViktorKuryshev/CRM
【问题讨论】:
-
你需要
await task而不是task.Wait并让你的事件处理程序是async void。 -
为什么
SwitchToProjectsPanelAsync方法是异步的?它没有等待? -
我建议您阅读有关 async 和 await 的内容。你没有正确使用它。
-
您需要使用
await。也就是说,一旦你解决了这个问题,你就会遇到你正在等待的async方法本身不是异步的问题,因此即使使用await,线程也会阻塞。你会想看看这样的帖子:stackoverflow.com/q/25295479、stackoverflow.com/q/34151399、stackoverflow.com/q/25295166、stackoverflow.com/q/12786758 等或任意数量的the rest you should've found had you bothered to search -
我已经阅读了两周,但它并没有帮助我理解如何在我的案例中应用它。现在有了你的 cmets,我明白了一点,谢谢。
标签: c# async-await