在异步操作期间更新网页

时间:2018-04-18 07:33:26

标签: c# asp.net async-await user-experience

我通过其公开的viewDidDLoad()方法异步使用网络服务,但我实际上无法按预期更新我的用户界面...

operationAsync

由于那些比我更有经验的人已经注意到,protected async void DownloadInfo_Click(object sender, EventArgs e) { // Change text of status label to reflect work being done. DownloadStatus.Text = "Connecting to service..."; using (var client = new Service.ServiceClient()) { DownloadStatus.Text = "Getting data..."; var response = client.DoOperation(args); // Handle the response in any way appropriate var control = new HtmlGenericControl(); control.InnerHtml = response.Value; DownloadStatus.Text = "Operation complete."; // Write the response from the service to the page. (testing) ResultDiv.Controls.Add(control); } } 标签文本在完成所有工作之前绝不会实际反映更新。

这并不能提供良好的用户体验,所以我需要找到一种不同的方式。

一个SO答案建议使按钮单击同步,但让它调用异步线程方法。听起来很奇怪但是UI更新将在事件处理程序上完成,而异步工作则在其他地方完成。

我还发现this question on ASP.NET谁的回答构建了一个帮助类来管理这类事情,但我不清楚如何在这里定义进度消息......对我来说似乎它们与示例相比非常固定。我必须为我希望我的应用程序执行的每个操作复制此代码,这意味着我的项目中存在大量膨胀。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您应该将您的asp.net代码放在UpdatePanel中。

阅读这些教程,了解如何正确使用它:Asp.net UpdatePanelIntroduction to UpdatePanel

以下是一个有关其工作原理的简单示例:

<asp:UpdatePanel ID="MyUpdatePanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
   <ContentTemplate>
       <label runat="server" id="MyLabel">LabelInfo</label>
       <asp:LinkButton ID="MyLinkButton" runat="server" OnClick="ChangeMyLabel_Click">Click me</asp:LinkButton>
   </ContentTemplate>
</asp:UpdatePanel>

protected void ChangeMyLabel_Click(object sender, EventArgs e)
{
   MyUpdatePanel.Update();
   MyLabel.Text = "Woah I just changed at runtime!!";
}