异步方法中的警告消息说它缺少等待操作符 [英] Warning message in async method saying that it lacks await operators

查看:35
本文介绍了异步方法中的警告消息说它缺少等待操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 asp.net mvc 4 应用程序中有一个 excel 下载.当我单击导出按钮时,将调用以下控制器方法.由于我需要异步完成,我在这里使用 async 和 await.

I have a excel download in my asp.net mvc 4 application. When I click the export button the below controller method gets called. Since I need it to be done asynchronous, I am using async and await here.

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,如下图

This method inturn call a excel generator method ReportExcelAsync as shown below

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; 
    }

但是我收到一条警告消息,作为警告

But I get a warning message as Warning

这种异步方法缺少await"操作符,将同步运行.考虑使用await"运算符来等待非阻塞 API 调用,或 'await Task.Run(...)' 在后台线程上执行 CPU 密集型工作

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 ?.My code works fine and I am able to get the excel downloaded.

推荐答案

我做错了吗?

好吧,你并没有真正异步地做任何事情.您的 ReportExcelAsync 方法是完全同步的,因为它没有任何 await 表达式.所以GenerateReportExcel会调用ReportExcelAsync,同步运行,然后返回一个完成的任务.您目前所做的只是添加少量开销来创建用于实现 async/await 的状态机等.

Well, you're not really doing anything asynchronously. Your ReportExcelAsync method is entirely synchronous, as it doesn't have any await expressions. So GenerateReportExcel will call ReportExcelAsync, which will run synchronously, and then return a completed task. All you've done at the moment is add a small amount of overhead for creating the state machine etc that is used to implement async/await.

不清楚为什么您期望它实际上异步发生,但我怀疑这是对 await/async 实际作用的误解.它不会自动为您启动新线程 - 它只是让创建和使用异步 API 变得更加容易.

It's not clear why you expected it to actually happen asynchronously, but I suspect it's a misunderstanding of what await/async actually does. It doesn't start up new threads for you automatically - it just makes it much easier to create and consume asynchronous APIs.

现在一个选择是只想将 ReportExcelAsync 更改为同步方法(ReportExcel,返回一个 string)并创建一个新任务为此在调用代码中:

Now one option is to just want to change ReportExcelAsync into a synchronous method (ReportExcel, returning a string) and create a new task for that in the calling code:

var filePath = await Task.Run(excel.ReportExcel);

然而,目前尚不清楚这实际上会给您带来多少好处.您正在编写一个网络应用程序,因此不会像这样更快地提供响应 - 您实际上只是转移完成工作的线程.

However, it's not clear that this would actually give you much benefit. You're writing a web app, so it's not like the response is going to be delivered any faster this way - you're effectively just shifting the thread the work is done on.

你说:

因为我需要异步完成

...但没有理由为什么它需要异步完成.在这种情况下,同步方法有什么问题?在适当的时候异步是很好的,但我不认为你的情况是这样.

... but give no reasons why it needs to be done asynchronously. What's wrong with the synchronous approach in this case? Asynchrony is great when it's appropriate, but I don't think it is in your case.

这篇关于异步方法中的警告消息说它缺少等待操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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