ASP.NET异步标签更新

我有一个运行时间很长的进程,我想在进程过程中更新页面上的标签,但我没有运气。

这是aspx:

       

这是背后的代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; namespace Website.structureDoc { public partial class Async : System.Web.UI.Page { BackgroundWorker backgroundWorker1; protected void Page_Load(object sender, EventArgs e) { backgroundWorker1 = new BackgroundWorker(); backgroundWorker1.WorkerReportsProgress = true; backgroundWorker1.WorkerSupportsCancellation = true; } protected void startAsyncButton_Click(object sender, EventArgs e) { if (backgroundWorker1.IsBusy != true) { // Start the asynchronous operation. backgroundWorker1.RunWorkerAsync(); } } protected void cancelAsyncButton_Click(object sender, EventArgs e) { if (backgroundWorker1.WorkerSupportsCancellation == true) { // Cancel the asynchronous operation. backgroundWorker1.CancelAsync(); } } // This event handler is where the time-consuming work is done. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; i <= 10; i++) { if (worker.CancellationPending == true) { e.Cancel = true; break; } else { // Perform a time consuming operation and report progress. System.Threading.Thread.Sleep(500); worker.ReportProgress(i * 10); } } } // This event handler updates the progress. private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { resultLabel.Text = (e.ProgressPercentage.ToString() + "%"); } // This event handler deals with the results of the background operation. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled == true) { resultLabel.Text = "Canceled!"; } else if (e.Error != null) { resultLabel.Text = "Error: " + e.Error.Message; } else { resultLabel.Text = "Done!"; } } } } 

背景工人不是正确的做法吗?

如果可能的话,我宁愿不使用AJAX这样做。

这不会起作用。 问题是asp.net在请求/响应模型上工作。 为了接收任何更新,客户端(浏览器)需要从服务器请求信息。 为了更新您的标签,您需要向服务器发送其新值的请求,然后该值将显示该值,并以适当的值进行响应以供您显示。

最简单的方法是使用AJAX以某种方式对数据请求进行计时,或者设置计时器并使页面在设置计时器上刷新。 底线是您需要页面轮询更新的值,只是因为您更新工作进程中的值并不意味着浏览器将接收此新值。

我知道你说你不想使用AJAX但是看看下面的jQuery.get()来更好地理解你需要做什么。

您可以使用SignalR library来实现此function。

请在此处查看示例

在给定的示例中,在服务器端dosomething()异步任务完成后,它调用客户端notifyResult()来更新视图。

另请参阅: 有没有办法从SignalR中的Clients.method调用中排除客户端?