我试图了解 async await 的用法,我研究了一些博客文章,现在我已经制作了一个测试代码,但它并没有按照我期望的方式工作。
我有一个返回列表的方法:
private List<Employee> GetEmployees()
{
IList<Employee> list = new List<Employee>();
list.Add(new Employee() { Id = 1, Age = 20, Name = "Kavin" });
list.Add(new Employee() { Id = 2, Age = 30, Name = "Alen" });
list.Add(new Employee() { Id = 3, Age = 20, Name = "Suresh" });
list.Add(new Employee() { Id = 4, Age = 30, Name = "Jay" });
list.Add(new Employee() { Id = 5, Age = 20, Name = "Nanda" });
list.Add(new Employee() { Id = 5, Age = 20, Name = "Kavin" });
list.Add(new Employee() { Id = 5, Age = 20, Name = "Kavin" });
list.Add(new Employee() { Id = 1, Age = 23, Name = "Test" });
return list;
}
然后我写了我的异步方法:
private async Task<List<Employee>> TestEmployeesGetAsync()
{
var result = await Task.Run(() => GetEmployees());
return result;
}
当我调用这个方法时:
var Result = TestEmployeesGetAsync();
Visual Studio 告诉我它返回了 Task<List<T>>
它的用法是:
List<Employee> result = await TestEmployeesGetAsync();
为什么我需要在调用方法上放置 await 如果我放置 await
它当然会给出编译器错误,因为 await
也应该有异步。有人能让我清醒一下怎么调用它,这样我就可以得到 List<T>
而不是 Task<List<T>>
最佳答案
Why i need to put await on the calling method if i put await it gives compiler error of course because await should have async as well.
编译器需要一些依赖项来了解您正在运行异步方法。信号是方法声明中的 async
修饰符。一旦将其标记为 async
,就可以使用 await
关键字。这就是异步“一路”向下传播到调用堆栈的原因,因为当您调用一个异步方法并需要等待其结果时,您需要使用 async 修饰符标记使用方法。
为了使您的方法有效,您需要执行以下操作:
public async Task GetEmployeesAsync()
{
List<Employees> result = await TestEmployeesGetAsync();
}
作为旁注,请注意 you should not expose async wrappers over sync methods .
关于c# - async await 在调用异步方法时返回 Task<List<T>> 而不是 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309716/