在后台运行功能并继续运行默认程序流

问题描述 投票:0回答:1

我有基本的Excel文件制作功能,带有2个日期参数

public void ExportToExcel(DateTime? start, DateTime? end) 

但是此功能需要很长时间,我不想等待这个准备时间。我希望此函数在后台运行,而不冻结我的actionResult

        public ActionResult Listele(DateTime? dates, DateTime? datee,string submit)
        {
                var model = db.Transections.ToList();

                DateTime startdate = dates ?? new DateTime(2000, 10, 10, 1, 1, 1, 1);
                DateTime enddate = datee ?? DateTime.Now; ;
                foreach (var item in model.ToList())
                {
                    if (item.Date < startdate || item.Date > enddate)
                    {
                        model.Remove(item);

                    }
                }
                Debug.WriteLine(model.Count());
            if(submit == "report")
                {
                return RedirectToAction("ExportToExcel", "Grid", new { @start = dates, @end = datee });
            }

                return View(model);

        }

此操作结果必须正在运行,不会因等待此功能而冻结和我的行动前端


@model IEnumerable<codefirst.Models.Transection>
@using GridMvc.Html
@{
   ViewBag.Title = "Listele";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Listele</h2>


<form action="/Grid/Listele" method="get">
   <div class="form-group>
       <label for="q">Start Date</label>
       <input type="date" name="dates" id="dates" class="form-control" />
       <label for="q">End Date</label>
       <input type="date" name="datee" id="datee" class="form-control" />

   </div>
   <input class="btn btn-primary" type="submit" value="cek" name="submit" />
   <input class="btn btn-primary" type="submit" value="report" name="submit" />

@*    @Html.ActionLink("Report", "ExportToExcel", "Grid")*@
</form>




@Html.Grid(Model).Columns(Column =>
  {
      Column.Add(m => m.Buyer).Titled("Buyer").Sortable(true).Filterable(true);
      Column.Add(m => m.Seller).Titled("Seller").Sortable(true).Filterable(true);
      Column.Add(m => m.Amount).Titled("Amount").Sortable(true).Filterable(true);
      Column.Add(m => m.Date).Titled("Date").Sortable(true).Filterable(true).Format("{0:d}");
      Column.Add().Format("{0:MM/dd/yyyy}")
      .Encoded(false)
      .Sanitized(false)
      .SetWidth(30)
      .RenderValueAs(o => Html.ActionLink("Düzenle", "Duzenle", "Grid", new { id = o.id }, new { @class = "btn btn-warning" }));
  }).WithPaging(50)

ım尝试以这种方式异步运行,但excel方法仅正确运行,但ı无法触发此功能异步运行


       public void ExportToExcelasync(DateTime? start, DateTime? end)
       {
           Debug.WriteLine("async geldi");
           Debug.WriteLine(start);
           Debug.WriteLine(end);
           System.Threading.Tasks.Task.Run(() => ExportToExcel(start,end));
       }

       public void ExportToExcel(DateTime? start, DateTime? end)

它是我的exportexcel函数

public void ExportToExcel(DateTime? start, DateTime? end)
       {
           Debug.WriteLine("Export To Excel çaılıştı");

           Debug.WriteLine(start);
           Debug.WriteLine(end);
           /*
           for (int i = 0; i < 10000; i++)
           {
               Debug.Write(i);
           }

           */


           try
           {//Downloads tablosuna indirmenin kaydı


               Download m = new Download();



               DateTime startdate = start ?? new DateTime(2000, 10, 10, 1, 1, 1, 1); ;

               DateTime enddate = end ?? DateTime.Now;

               Debug.WriteLine(startdate);
               Debug.WriteLine(enddate);
               //each caseler eklenecek seçmezse geçersiz seçerse end date start date den buyukse startla end date degıstırme eklencek




               DateTime now = DateTime.Now;
               //string trim = text.Replace( " ", "_" );
               m.IsExist = false;
               m.CreateDate = now;
               m.EndDate = now;
               m.StartDate = now;
               string name = "Report";
               string date = now.ToString("F");
               date = date.Replace(" ", "_");
               date = date.Replace(",", "_");
               string sonu = ".xls";
               date += sonu;
               name += date;
               m.GuidName = name;
               db.Downloads.Add(m);
               db.SaveChanges();

               //Excelin hazırlanması

               var gv = new GridView();
               var temp = db.Transections.ToList();




               // start 2010  ///// end 2015
               foreach (var item in temp.ToList())
               {
                   if (item.Date < startdate || item.Date > enddate)
                   {
                       temp.Remove(item);

                   }
               }

               gv.DataSource = temp;
               gv.DataBind();
               Response.ClearContent();
               Response.Buffer = true;
               string attachment = "attachment; filename=";
               attachment = attachment + name;
               //attachment = "\"" + attachment +"\"";
               Response.AddHeader("content-disposition", attachment);
               Response.ContentType = "application/ms-excel";
               Response.Charset = "";
               StringWriter objStringWriter = new StringWriter();
               HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
               gv.RenderControl(objHtmlTextWriter);
               Response.Output.Write(objStringWriter.ToString());
               Response.Flush();
               Response.End();

               /*

               Download download = new Download();
               download = db.Downloads.Find(m.GuidName);
               download.IsExist = true;
               db.Entry(download).State = System.Data.Entity.EntityState.Modified;
               db.SaveChanges();

               */
               //Debug.WriteLine(download.IsExist);





               { /*
               public ActionResult UpdateCustomer(Customer customer)
               {
                   using (CustomersEntities entities = new CustomersEntities())
                   {
                       Customer updatedCustomer = (from c in entities.Customers
                                                   where c.CustomerId == customer.CustomerId
                                                   select c).FirstOrDefault();
                       updatedCustomer.Name = customer.Name;
                       updatedCustomer.Country = customer.Country;
                       entities.SaveChanges();
                   }
                   */
               }
               Debug.WriteLine("Return geldi");



               //return NonActionAttribute();
           }
           catch (Exception ex)
           {
               Debug.WriteLine(ex);
               //exception loglanacak
               //return View("Index");

           }


       }

Response.AddHeader(“ content-disposition”,附件);这行是一个例外,例外是


Exception thrown: 'System.ArgumentException' in System.Web.dll
System.ArgumentException: Value does not fall within the expected range.
  at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
  at System.Web.Hosting.IIS7WorkerRequest.SetUnknownResponseHeader(String name, String value, Boolean replace)
  at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
  at System.Web.HttpHeaderCollection.Add(String name, String value)
  at System.Web.HttpResponse.AppendHeader(String name, String value)
  at System.Web.HttpResponseWrapper.AddHeader(String name, String value)
  at codefirst.Controllers.GridController.ExportToExcel(Nullable`1 start, Nullable`1 end) in C:\Users\nto_9\source\repos\codefirst\codefirst\Controllers\GridController.cs:line 176

此异常ı无法理解的原因是什么,以及它将如何让您看到我ı错过了帮助

异常看起来像调试器exception on debugger

ımtryıngto async await

像这样更改我的异步方法并将像这样的export更改为excel方法,但是它仍然不能正常工作,这仍然是我为fexport转换为excel方法所采取的行动结果,您能看到我的错误吗?

我的异步通话功能

       public async Task ExportToExcelasync(DateTime? start, DateTime? end)
       {
           Debug.WriteLine("async geldi");
           Debug.WriteLine(start);
           Debug.WriteLine(end);
           await Task.Run(() => ExportToExcel(start, end));
       }

我导出到excel func

public void ExportToExcel(DateTime? start, DateTime? end)
       {
           Debug.WriteLine("Export To Excel çaılıştı");

           Debug.WriteLine(start);
           Debug.WriteLine(end);

           for (int i = 0; i < 10000; i++)
           {
               Debug.Write(i);
           }




           try
           {//Downloads tablosuna indirmenin kaydı


               Download m = new Download();



               DateTime startdate = start ?? new DateTime(2000, 10, 10, 1, 1, 1, 1); ;

               DateTime enddate = end ?? DateTime.Now;

               Debug.WriteLine(startdate);
               Debug.WriteLine(enddate);
               //each caseler eklenecek seçmezse geçersiz seçerse end date start date den buyukse startla end date degıstırme eklencek




               DateTime now = DateTime.Now;
               //string trim = text.Replace( " ", "_" );
               m.IsExist = false;
               m.CreateDate = now;
               m.EndDate = now;
               m.StartDate = now;
               string name = "Report";
               string date = now.ToString("F");
               date = date.Replace(" ", "_");
               date = date.Replace(",", "_");
               string sonu = ".xls";
               date += sonu;
               name += date;
               m.GuidName = name;
               db.Downloads.Add(m);
               db.SaveChanges();

               //Excelin hazırlanması

               var gv = new GridView();

               var temp = db.Transections.ToList();

               // start 2010  ///// end 2015
               foreach (var item in temp.ToList())
               {
                   if (item.Date < startdate || item.Date > enddate)
                   {
                       temp.Remove(item);

                   }
               }

               gv.DataSource = temp;
               gv.DataBind();
               Response.ClearContent();
               Response.Buffer = true;
               string attachment = "attachment; filename=";
               attachment = attachment + name;
               //attachment = "\"" + attachment +"\"";
               Response.AddHeader("content-disposition", attachment);
               Response.ContentType = "application/ms-excel";
               Response.Charset = "";
               StringWriter objStringWriter = new StringWriter();
               HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
               gv.RenderControl(objHtmlTextWriter);
               Response.Output.Write(objStringWriter.ToString());
               Response.Flush();
               Response.End();


           }
           catch (Exception ex)
           {

           }
       }

asp.net-mvc actionresult
1个回答
1
投票
在这种情况下,异步和等待可能会有所帮助。请转到下面的链接。

https://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/

© www.soinside.com 2019 - 2024. All rights reserved.