How to update UI immediately when running an async task

亡梦爱人 提交于 2021-02-08 09:58:13

问题


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!";
}

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.


回答1:


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:

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

• 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 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>


来源:https://stackoverflow.com/questions/40348204/how-to-update-ui-immediately-when-running-an-async-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!