最佳实践-警告:方法缺少“等待"操作员警告 [英] Best practice - warning: method lacks 'await' operator warning
问题描述
是的,我知道还有其他问题可以解决此警告的含义以及如何解决它,但是,我有一个关于异步编程的最佳实践的问题.
Yes, I know there are other questions to cover what this warning means and how to solve it, however, I have a question about best practices regarding async programming.
我有一个服务层,负责处理数据层和表示层之间的数据传输.该服务包含几种查询数据库并返回结果的方法.
I have a service layer which handles data transfer between the data layer and the presentation layer. This service contains several methods which query the database, and return the result.
我一直在尝试使用异步编程.一个例子:
I have been trying to use async programming wherever possible. An example:
public async Task<SiteTemplateResource[]> GetResources(int siteTemplateId, string extension)
{
return await Database.FindBy<SiteTemplateResource>(str => str.SiteTemplateId == siteTemplateId && str.HashedFile.EndsWith(extension)).ToArrayAsync();
}
我的问题是,除了 ToArrayAsync
调用之外,我实际上没有等待任何事情,而我真的不需要.
My problem with this is, I'm not actually awaiting anything, other than to the ToArrayAsync
call, which I don't really need.
我应该继续使用异步/等待吗?例如,我将如何等待此功能的任何结果:
Should I go ahead and use async/await for this? And how would I for example await anything for this function:
public async Task<int> SiteTemplateBySiteIdAsync(int siteId)
{
return Database.First<SiteSiteTemplate>(sst => sst.SiteId == siteId).SiteTemplateId;
}
在该函数中我什么都不需要等待,但是我也不需要调用 ToArrayAsync
,因此在上述情况下如何避免出现方法缺少'await'运算符"警告?
I don't await anything in that function, but I also don't need to call ToArrayAsync
, so how do I avoid the warning "method lacks 'await' operator" in above case?
谢谢.
推荐答案
如果您不需要通过某种方法进行 await
,则该方法需要 async
(无论出于何种原因),您可以使用 Task.FromResult
,可以等待:
If you have nothing to await
in a method that needs to be async
(for whatever reason), you can use Task.FromResult
, which can be awaited:
public async Task<int> SiteTemplateBySiteIdAsync(int siteId)
{
return await Task.FromResult(Database.First<SiteSiteTemplate>(sst => sst.SiteId == siteId).SiteTemplateId);
}
如果不需要 async
方法,则可以简单地添加 async Task< int>
并将其替换为 int
.
If you don't need the async
method, you can simply more the async Task<int>
and replace it for int
.
这篇关于最佳实践-警告:方法缺少“等待"操作员警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!