此异步方法缺少“等待"运算符,将同步运行 [英] This async method lacks 'await' operators and will run synchronously
问题描述
我的程序对以下语句有3条警告:
my program has 3 warnings of the following statement:
此异步方法缺少等待"运算符,将同步运行. 考虑使用"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.
尝试告诉我什么警告?我该怎么办?
What is the warning try to tell me? What should I do?
这是我的代码:它是否在使用多线程运行?
This is my code: Is it running using multi-threading?
static void Main(string[] args)
{
Task task1 = new Task(Work1);
Task task2 = new Task(Work2);
Task task3 = new Task(Work3);
task1.Start();
task2.Start();
task3.Start();
Console.ReadKey();
}
static async void Work1()
{
Console.WriteLine("10 started");
Thread.Sleep(10000);
Console.WriteLine("10 completed");
}
static async void Work2()
{
Console.WriteLine("3 started");
Thread.Sleep(3000);
Console.WriteLine("3 completed");
}
static async void Work3()
{
Console.WriteLine("5 started");
Thread.Sleep(5000);
Console.WriteLine("5 completed");
}
推荐答案
async
关键字本身并不能真正起到很大作用.从您的代码中删除它,您的代码将完全相同.
The async
keyword, by itself, doesn't really do much. Remove it from your code and your code will act exactly the same.
async
的作用是什么?
- 它更改了方法内部的有效内容,特别是它允许您使用
await
关键字 - 反过来,这意味着将根据方法主体中存在的
await
来转换方法主体. - 如果该方法返回值,则该方法也将转换为将返回值包装在
Task
中.
- It changes what's valid inside of the method, specifically it allows you to use the
await
keyword - In turn, it means that the body of the method will be transformed, based on the
await
s that are present in the body of the method. - And if the method returns a value, the method is also transformed to wrap the return value in a
Task
.
但是,如果您a)方法主体中没有任何await
,并且b)返回了void
,那么将不会实现任何特殊操作.编译器警告确实尝试澄清这一点-没有任何await
的async
方法没有任何意义. await
s是此功能的更重要部分.
However, if you a) Don't have any await
s in your method body and b) are void
returning, then nothing special will be achieved. The compiler warning does try to be clear about this - an async
method without any await
s just plain doesn't make sense. await
s are the more important part of this feature.
这篇关于此异步方法缺少“等待"运算符,将同步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!