public async Task<ActionResult> GenerateReportExcel()
{
ExcelGenerator excel = new ExcelGenerator();
var filePath = await excel.ReportExcelAsync(midyearReportViewModel);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xlsx;", PdaResource.ReportFileName));
response.TransmitFile(filePath);
response.Flush();
response.End();
return PartialView("_MidYearReportPartial", midyearReportViewModel);
}
这个方法inturn调用一个excel生成器方法ReportExcelAsync,如下所示
public async Task<string> ReportExcelAsync(MidYearReportViewModel _midyearAnnualviewModel)
{
string fileName = "MidYearReport";
string finalXcelPath = string.Empty;
string currentDirectorypath = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Export")).ToString();
finalXcelPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName);
if (System.IO.File.Exists(finalXcelPath))
{
System.IO.File.Delete(finalXcelPath);
}
var newFile = new FileInfo(finalXcelPath);
using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
{
using (var package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(resxSet.GetString("ReportMYMidYearExcelSheetName"));
for (int i = 1; i <= header.Count(); i++)
{
worksheet.Cells[1, i].Value = header[i - 1];
worksheet.Cells[1, i].Style.Font.Bold = true;
worksheet.Cells[1, i].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, i].Style.Font.Color.SetColor(Color.White);
worksheet.Cells[1, i].Style.Fill.BackgroundColor.SetColor(Color.DimGray);
}
package.Save();
}
}
return finalXcelPath;
}
但我收到警告消息作为警告
This async method lacks ‘await’ operators and will run synchronously.
Consider using the ‘await’ operator to await non-blocking API calls,
or ‘await Task.Run(…)’ to do CPU-bound work on a background thread
。我做错了什么?我的代码工作正常,我可以下载excel。
Am I doing something wrong?
嗯,你不是真的做异常的事情。您的ReportExcelAsync方法是完全同步的,因为它没有任何等待表达式。所以GenerateReportExcel将调用ReportExcelAsync,它将同步运行,然后返回一个已完成的任务。您目前所做的一切都是为了创建用于实现异步/等待的状态机等增加了少量开销。
不清楚为什么你期望它实际上是异步发生的,但我怀疑这是对等待/异步实际发生的误解。它不会自动启动新线程 – 它只是使得创建和使用异步API更容易。
现在一个选择是将ReportExcelAsync更改为同步方法(ReportExcel,返回一个字符串),并为调用代码创建一个新任务:
var filePath = await Task.Run(excel.ReportExcel);
然而,这并不清楚,这实际上会给你很大的好处。你正在编写一个网络应用程序,所以不像以前那样更快地发送响应 – 你只是将线程转换成完成的工作。
你说:
Since I need it to be done asynchronous
…但没有任何理由需要异步地完成。在这种情况下,同步方法有什么问题?不合时宜适合,但我不认为这是你的情况。
相关文章
转载注明原文:c# – 异步方法中的警告消息,表示它缺少等待操作符 - 代码日志