运行异步任务时如何立即更新UI

编程入门 行业动态 更新时间:2024-10-28 12:16:38
本文介绍了运行异步任务时如何立即更新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

本文发布于:2023-11-09 03:02:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571217.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:UI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!