【问题标题】:Update webpage during async operation在异步操作期间更新网页
【发布时间】:2018-04-21 02:47:07
【问题描述】:

我正在通过其公开的 operationAsync 方法异步使用 Web 服务,但我并不能真正按预期更新我的 UI...

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

正如那些比我更有经验的人已经注意到的那样,DownloadStatus 标签文本在所有工作完成之前永远不会真正反映更新。

这并不能真正带来良好的用户体验,因此我需要找到不同的方法。

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

我还发现 this question on ASP.NET 的答案构建了一个帮助类来管理这类事情,但我不太清楚如何在这里定义进度消息......在我看来,它们几乎是固定的例如。我必须为我希望我的应用程序执行的每个操作复制此代码,这意味着我的项目会出现很多膨胀。

我们将不胜感激。

【问题讨论】:

  • operationAsync 的电话在哪里?该代码是否有任何编译警告?

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


【解决方案1】:

您应该将您的 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!!";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2018-09-30
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多