![](/img/trans.png)
[英]Async method lacks await operators warning when the await is in a function passed to an async lambda expresion
[英]Warning message in async method saying that it lacks await operators
我在我的asp.net mvc 4應用程序中有一個excel下載。 當我單擊導出按鈕時,將調用以下控制器方法。 因為我需要異步完成,所以我在這里使用異步並等待。
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);
}
此方法調用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;
}
但是我收到警告信息警告
這種異步方法缺少“等待”運算符並將同步運行。 考慮使用'await'運算符等待非阻塞API調用,或'await Task.Run(...)'在后台線程上執行CPU綁定工作
。 我做錯了什么?。我的代碼工作正常,我能夠下載excel。
難道我做錯了什么?
好吧,你並沒有真正做任何異步的事情。 ReportExcelAsync
方法完全同步,因為它沒有任何await
表達式。 因此, GenerateReportExcel
將調用ReportExcelAsync
,它將同步運行,然后返回已完成的任務。 您目前所做的就是添加少量開銷來創建用於實現async
/ await
的狀態機等。
目前尚不清楚為什么你期望它實際上是異步發生的,但我懷疑它是對await / async實際上做什么的誤解。 它不會自動為您啟動新線程 - 它只是使創建和使用異步API變得更加容易。
現在一個選項是只想將ReportExcelAsync
更改為同步方法( ReportExcel
,返回一個string
)並在調用代碼中為其創建一個新任務:
var filePath = await Task.Run(excel.ReportExcel);
但是,目前尚不清楚這會給你帶來多少好處。 你正在編寫一個網絡應用程序,所以它不像響應會以這種方式更快地傳遞 - 你實際上只是轉移工作完成的線程。
你說:
因為我需要它以異步方式完成
...但沒有理由說明為什么需要異步完成。 在這種情況下同步方法有什么問題? 在適當的時候異步很棒,但我不認為它適合你的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.