运行异步任务时如何立即更新UI [英] How to update UI immediately when running an async task

查看:63
本文介绍了运行异步任务时如何立即更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有报表的Asp.Net 4.5 Webforms应用程序,我正在尝试使用异步等待运行该报表.这是我使用的代码示例:

I have an Asp.Net 4.5 webforms application with a report which I'm trying to run using async await. Here is an example of the code I'm using:

protected async void btnReport_Click(object sender, EventArgs e)
{
    lblStatus.Text = "Working!";
    await LongRunningTask();
}

private async Task LongRunningTask()
{
    await Task.Delay(5000);
    lblStatus.Text = "Done!";
}

我阅读的所有内容似乎都建议第一种方法应立即完成并更新标签,但事实并非如此.该方法仍然绑定UI,直到LongRunningTask完成.如果我从btnReport_Click中删除异步并等待,则UI会立即更新,但LongRunningTask完成时,我会得到未处理的异常,没有任何特定信息.请让我知道我在这里不了解的内容.

Everything I've read seems to suggest that the first method should complete immediately and update the label but this is not the case. The method still ties up the UI until LongRunningTask completes. If I remove async and await from btnReport_Click the UI is updated immediately but then I get an unhandled exception with no specific information when LongRunningTask completes. Please let me know what I am not understanding here.

推荐答案

我有类似的问题要求.解决了没有ajax或JavaScript并使用4.5框架的问题.以下是一些建议给那些可能读到这些的人的建议:

I had a similar problem requirement. Solved without ajax or JavaScript and using 4.5 framework. Here’s some advice to those that may read this:

•确保您的page.aspx声明具有以下内容:<%@页面标题=" Async ="true"

• Make sure your page.aspx declaration has this: <%@ Page Title="" Async="true"

•确保您的按钮处理程序受保护的异步void MyButton(对象发送者,EventArgs e)

• Make sure your button handler is protected async void MyButton(object sender, EventArgs e)

•在我的情况下,虽然可能不是一个坏主意,但我没有使用更新面板.基本示例代码:

• In my situation I did not use update panels although may not be a bad idea. Basic sample code:

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected async void Button1_Click(object sender, EventArgs e)
    {
        string s = await GetAsyncMethod1();
        Label1.Text = s;
        //Or call this 
        //string s = await GetAsyncMethod2(); 
    }


    private string GetDataFromDB()
    {
        return  "Heres your data...";
    }

    private Task<string> GetAsyncMethod1()
    {
        //dbLayer
       return Task.Run(() => GetDataFromDB());
    }

    public async Task<string> GetAsyncMethod2()
    {
        //Optional business Layer - more processing
        string complicated = "";
        complicated = await GetAsyncMethod1();
        return complicated;

    }

.... aspx标记:

....aspx mark-up:

<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"  OnClick="Button1_Click"/>
        <asp:Label ID="Label1" runat="server" Text="Label" />
    </div>
    </form>

这篇关于运行异步任务时如何立即更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆