使用BackgroundWorker时GUI挂起

时间:2013-01-30 10:15:39

标签: .net-3.5 backgroundworker

我无法让这个BackgroundWorker为我工作。我正在使用here

中的 m3rLinEz 示例

问题是GUI没有响应,百分比没有更新。

我正在使用母版页,我在内容页面的标题中设置了async="true" 我错过了别的什么吗?

ASPX代码:

<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnClick_Go" />&nbsp;
<asp:Label runat="server" id="textUpdate" text="0%" />

背后的代码

protected void btnClick_Go(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)
    {
        textUpdate.Text = string.Format("{0}%", args.ProgressPercentage);
    });

    // what to do when worker completes its task (notify the user)
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
    delegate(object o, RunWorkerCompletedEventArgs args)
    {
        lblSuccess.Visible = true;
    });

    bw.RunWorkerAsync();
}

1 个答案:

答案 0 :(得分:2)

BackgroundWorker通常用于客户端UI - WPF,WinForms等。

在您的代码中,您尝试在将响应发送回客户端后更新UI 。如果没有客户端到服务器的后续请求,您希望如何工作?

说到Web应用程序,您需要使用AJAX来不断更新UI。可能有很好的方法可以让AJAX易于管理,但你不能只在服务器端使用BackgroundWorker并希望它一切正常。