【问题标题】:Why does my ajax call takes so long?为什么我的 ajax 调用需要这么长时间?
【发布时间】:2016-09-19 09:04:55
【问题描述】:

当我进行 AJAX 调用以接收此 c# 代码中定义的 JSON 对象时,我必须在 46 秒以上才能接收此对象。对象本身只有 12kb 大。是因为我的 c# 代码(执行时间不长吗?)还是别的原因。我在我的本地 IIS 服务器上对其进行测试。

这是我的代码:

[AcceptVerbs(HttpVerbs.Post)]
    public JsonResult LoadAudit(int id, string sheet)
    {
        FactsCustomerRepository<Cateringaudit> repo = new FactsCustomerRepository<Cateringaudit>();
        //IQueryable<Cateringaudit> result = repo.GetAll(i => i.State == 1);
        Cateringaudit result1 = repo.Get(id);
        WorkBook wb = new WorkBook();
        wb.read(new MemoryStream(result1.ExcelData));
        object[] jsonObjects = new object[3];
        //sheetnames to collect data from
        string[] sheetNames = { "contract", "proces", "output" };
        //itterate trough all sheets in excel file
        for (int sheetCount = 0; sheetCount < sheetNames.Length; sheetCount++)
        {
            wb.Sheet = wb.findSheetByName(sheetNames[sheetCount]);
            //Create new array with same lenght as rows with data
            Dictionary<string, string[]> excelData = new Dictionary<string, string[]>();
            //iterate trough all rows in worksheet
            for (int i = 1; i < wb.LastRow + 2; i++)
            {
                excelData.Add(blabla);
                jsonObjects[sheetCount] = excelData;
            }
        }
        return Json(jsonObjects);
    }

【问题讨论】:

  • 问题是否需要上述所有代码?
  • 尝试记录重要行的每一步。日志应该有时间戳。然后,您可以从那里进行调查。
  • 问题在哪里引用了上面的代码?这与 AJAX 完全无关。请修改您的问题
  • 使用代码分析器(例如 VS 中包含的一个)来查找代码中的瓶颈 - 从 repo 获取数据、使用 excel 等等。
  • 您可以调试该代码并检查需要这么长时间。您可以使用 StopWatch 类来获取该代码所需的确切时间。在我看来,这个问题与 ajax 调用无关,它与您在服务器端实现的逻辑有关,需要在将数据传递给客户端之前完成。

标签: c# .net json ajax


【解决方案1】:

在这里遇到困难:在 C# 中打开 Excelsheets 非常慢。有很多很棒的库,速度更快:

EEPLUS:http://epplus.codeplex.com/

但要先排除 Excel:您是否尝试过返回静态 JsonObject 而不使用 excel?

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult LoadAudit(int id, string sheet)
{
    return Json(); // something like this
}

【讨论】:

  • 确实是 Excel 让它这么慢,我返回了一个静态 JSON 对象。起初我使用的是 Spreadsheetlight,现在我使用的是 SmartXLS,我读到它比电子表格快得多。
猜你喜欢
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多