如何从后台工作者返回到asp.net中的Web UI

时间:2015-03-31 11:08:34

标签: c# asp.net response backgroundworker

当后台工作者完成时,asp.net中的后台工作程序不会将内容写入Web UI。请告诉我原因。以及如何恢复。???

static BackgroundWorker bwProcess; 

[WebMethod()]
public static int GetProgress()
{
      return Percentage;
}

后台工作程序在点击事件发生时启动

protected void btnClick_Click(object sender, EventArgs e)
    {

        bwProcess = new BackgroundWorker
        {
            WorkerReportsProgress = true,
            WorkerSupportsCancellation = true
        };

        bwProcess.DoWork += new DoWorkEventHandler(bwProcess_DoWork);
        bwProcess.ProgressChanged += new ProgressChangedEventHandler(bwProcess_ProgressChanged);
        bwProcess.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwProcess_RunWorkerCompleted);

        bwProcess.RunWorkerAsync("AsyncWorker");
    }

为背景工作者做工作活动

void bwProcess_DoWork(object sender, DoWorkEventArgs e)
        {
            bwProcess.ReportProgress(1);
            for (int i = 0; i <= 100; i++)
            {
                if (bwProcess.CancellationPending) 
                { 
                    e.Cancel = true; 
                    return;
                }
                bwProcess.ReportProgress(i);
                Thread.Sleep(20);
            }

            e.Result = "100 %";
        }

这部分不起作用。它运行坚果没有回应

void bwProcess_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            Response.WriteFile("D:\\Samples.xlsx");
        }

1 个答案:

答案 0 :(得分:0)

你已经在DoWork中向e.Result传递了一些内容,但在RunWorkerCompleted中你没有使用它。

void bwProcess_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     var text = e.Result as string;
     Response.Write(text);
     Response.WriteFile("D:\\Samples.xlsx");
}