如何在ASP.Net中使用后台工作程序 [英] how to use the Background Worker in ASP.Net

查看:79
本文介绍了如何在ASP.Net中使用后台工作程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在asp.net中使用 ajax 中的 BackgroundWorker 来从数据库中获取数据并将其导出到 excel 。当点击开始按钮时,后台工作人员将开始从数据库加载数据,并在excel将下载的流程完成时写入excel。这些过程显示通过进度条使用。



但是 httpcontext 中的问题(可能是错误的),当单击开始按钮excel文件已创建但不下载。请修复 问题。

i给出代码



i wants to use the BackgroundWorker in asp.net with ajax to get the data from the data base and export it into excel. when click the start button backgound worker will start load the data from database and write into excel when process complete that excel will download. these process show to use through Progress bar.

but problem in httpcontext(it may wrong), when click the start button excel file are created but it's not download. please fix the problem.
i given the code

 protected void Page_Load(object sender, EventArgs e)   
    {
        _backgroundWorker.WorkerReportsProgress=true;
        _backgroundWorker.WorkerSupportsCancellation = true;
        _backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
        _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
        _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
      
      
    }

protected void btnStart_Click(object sender, EventArgs e)
    {

        // Start(ProgressBar1.Progress, HttpContext.Current);
        if (!_backgroundWorker.IsBusy)
        {
            _backgroundWorker.RunWorkerAsync();
        }

    }

    void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        string display = "Message Pop-up!";
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
    }

    void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

        ProgressBar1.SetProgress(e.ProgressPercentage);


    }

    void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {

        Start(ProgressBar1.Progress, _httpContext);
    }







    private void Start(Progress progress, HttpContext context)
     {
        ProductBussiness productBussiness = new ProductBussiness();
        DataTable dataTable = new DataTable();
        StringBuilder builder = new StringBuilder();
        Table htmltable=new Table();

        int Totalcount = productBussiness.GetCount();
        int page = Totalcount / 100;
        double progresPercent = 100.00 / page;
        for (int i = 1; i <=page; i++)
        {
             dataTable = productBussiness.GetProductData(i);
             int percent=(int)(i * progresPercent);
            _backgroundWorker.ReportProgress(percent, progress);



            progress.SetProgress((i * progresPercent)/100);
            if(i<=page)
                ConvertToHtmlTable(dataTable, htmltable, builder, false, context);
            else
                ConvertToHtmlTable(dataTable, htmltable, builder, true, context);

        }
 
    }

    #endregion

  


   

    public StringBuilder ConvertToHtmlTable(DataTable dt, Table table, StringBuilder builder, bool end, HttpContext context)
      {
               if (dt.Rows.Count == 0)
               {
                    return null;//`enter code here`
               }

               if (table != null)
               {
                   foreach (DataRow r in dt.Rows)
                   {
                       builder.Append("<tr align='left' valign='top'>");
                       foreach (DataColumn c in dt.Columns)
                       {
                           builder.Append("<td align='left' valign='top'>");
                           builder.Append(r[c.ColumnName]);
                           builder.Append("</td>");
                       }
                       builder.Append("</tr>");
                   }
               }
               if (end)
               {
                   context.Response.Clear();
                   StringBuilder str1 = new StringBuilder();

                   str1.Append("<html>");
                   str1.Append("<head>");
                   str1.Append("<title>");
                   str1.Append("Page-");
                   str1.Append(Guid.NewGuid().ToString());
                   str1.Append("</title>");
                   str1.Append("</head>");
                   str1.Append("<body>");
                   str1.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
                   str1.Append("style='border: solid 1px Silver; font-size: x-small;'>");
                   str1.Append("<th align='left' valign='top'>");
                   foreach (DataColumn c in dt.Columns)
                   {
                       str1.Append("<td align='left' valign='top'><b>");
                       str1.Append(c.ColumnName);
                       str1.Append("</b></td>");
                   }
                   str1.Append("</tr>");

                   str1.Append(builder);

                   str1.Append("</table>");
                   str1.Append("</body>");
                   str1.Append("</html>");

                  context.Response.ClearContent();
                  context.Response.ClearHeaders();
                  context.Response.BufferOutput = true;

                  context.Response.AddHeader("content-disposition", "attachment;filename=ExportData1.xls");
                  context.Response.Charset = "";
                  context.Response.ContentType = "application/vnd.xls";
                  context.Response.Write(str1);
                  // Response.Flush();
                  // Response.Close();
                  context.Response.End();

               }

            return builder;
       }





谢谢

Pandiyan



thank you
Pandiyan

推荐答案

您只能将html作为请求的一部分发送到客户端。您的请求只是启动线程,线程本身不作为http请求的一部分运行,因此无法写入客户端,包括下载文件或显示消息或以任何方式更新html。基本上你不能把东西推给客户,客户必须要求它们。



如果你想要某种进度条,你需要进行民意调查来自客户端的服务器,看看任务是否完成。 Google针对长时间运行的任务,包含进度指示器,提供您需要执行的操作的示例。或者您可以查看SignalR,因为该框架是为此类任务而设计的。
You can only send html to the client as part of a request. Your request just kicks off the thread, the thread itself is not running as part of an http request so can't write to the client, that includes downloading the file or showing a message or updating the html in any way. Basically you can't "push" things to the client, the client has to request them.

If you want some kind of progress bar you'll need to poll the server from the client to see if the task is done. Google for long running tasks with progress indicator for examples of what you need to do. Or you could look into SignalR as that framework is designed for this kind of task.


这篇关于如何在ASP.Net中使用后台工作程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆