【发布时间】:2014-04-29 12:31:34
【问题描述】:
我使用了这个有用的一段简单代码 post
它使用一个按钮和一个标签,标签应该报告“10%完成”……“20%完成”……等等。
当我调试时,代码被命中,但我的标签没有在浏览器上更新。
我尝试过使用和不使用更新面板,使用和不使用母版页。
protected void btnStartThread_Click(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
// this allows our worker to report progress during work
bw.WorkerReportsProgress = true;
// what to do in the background thread
bw.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
{
BackgroundWorker b = o as BackgroundWorker;
// do some simple processing for 10 seconds
for (int i = 1; i <= 10; i++)
{
// report the progress in percent
b.ReportProgress(i * 10);
Thread.Sleep(1000);
}
});
// what to do when progress changed (update the progress bar for example)
bw.ProgressChanged += new ProgressChangedEventHandler(delegate(object o, ProgressChangedEventArgs args)
{
label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
});
// what to do when worker completes its task (notify the user)
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate(object o, RunWorkerCompletedEventArgs args)
{
label1.Text = "Finished!";
});
bw.RunWorkerAsync();
【问题讨论】:
-
如果 HTML 已经通过网络发送到客户端,您希望如何更新它?您需要在客户端上使用 AJAX 来更新页面。
-
这就是为什么我认为页面上的脚本管理器和更新面板可以解决问题:/
-
应该的。我不记得完全了,你确定你不需要调用像 updatePanel.Update(); 这样的东西吗?还是类似的?
-
您需要使用 SignalR 之类的工具将该信号发送到客户端。
-
在客户端服务器Web应用程序中,服务器不发起与客户端的通信,它只响应客户端的请求。您可以通过使用 ajax 请求或带有信号器 asp.net/signalr/overview/guide-to-the-api/… 的服务器推送模式来实现您想要的客户端拉取模式
标签: c# asp.net multithreading backgroundworker