[英]c# async await strange warning CS1998: This async method lacks 'await' operators
i'm new to async programming, i get the below warning in this method, does somebody knows why this happens?我是异步编程的新手,我在这种方法中收到以下警告,有人知道为什么会这样吗? Thank you very much.非常感谢。
public async Task<List<T1>> StartSearchAsync()
{
....other code
searchRequests.ForEach(async s => {
products.AddRange(await SinglePageSearch(s));
});
return products;
}
warning CS1998: This async method lacks 'await' operators and will run synchronously.警告 CS1998:此异步方法缺少“等待”运算符,将同步运行。 Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.考虑使用“await”运算符来等待非阻塞 API 调用,或“await Task.Run(...)”在后台线程上执行 CPU 密集型工作。
Your await
is within a lambda expression, which is another function entirely to your StartSearchAsync
method.您的await
在 lambda 表达式中,这是另一个 function 完全属于您的StartSearchAsync
方法。
In fact you should not be passing an async
delegate to List<T>.ForEach
, as that converts the delegate to async void
, which is undesirable because the calling method cannot wait for the delegates to complete.实际上,您不应该将async
委托传递给List<T>.ForEach
,因为这会将委托转换为async void
,这是不可取的,因为调用方法无法等待委托完成。
A better option would be to use Enumerable.Select
, in combination with Task.WhenAll
:更好的选择是将Enumerable.Select
与Task.WhenAll
结合使用:
public async Task<List<T1>> StartSearchAsync()
{
....other code
var tasks = searchRequests.Select(SinglePageSearch);
var results = await Task.WhenAll(tasks);
foreach (result in results) products.AddRange(result);
return products;
}
Using this approach, Task.WhenAll
enumerates the Task
s generated by Select
, and creates another Task
that completes when each SinglePageSearch
has completed.使用这种方法, Task.WhenAll
枚举由Select
生成的Task
,并创建另一个Task
在每个SinglePageSearch
完成时完成。
Now StartSearchAsync
can await
their completion.现在StartSearchAsync
可以await
它们的完成。
And if products
is simply an empty list being used to amalgamate the results, you can simplify further:如果products
只是一个用于合并结果的空列表,您可以进一步简化:
public async Task<List<T1>> StartSearchAsync()
{
....other code
var results = await Task.WhenAll(searchRequests.Select(SinglePageSearch));
return results.SelectMany(x => x).ToList();
}
The compiler tells you that you can safely remove the async
keyword from the method signature since you are not using the await
keyword directly inside the StartSearchAsync()
method.编译器告诉您,您可以安全地从方法签名中删除async
关键字,因为您没有直接在StartSearchAsync()
方法中使用await
关键字。
You are indeed using await
in the delegate that you pass for ForEach
but this doesn't affect the compilation of the StartSearchAsync()
method.您确实在为ForEach
传递的委托中使用了await
,但这不会影响StartSearchAsync()
方法的编译。
The async
keyword is only used to enable you to await
methods in the method or delegate that you mark as async
. async
关键字仅用于使您能够await
您标记为async
的方法或委托中的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.