[英]How work with async await in console app C#
This is the method inside the repository:这是存储库中的方法:
public async Task<IEnumerable<T>> FindAll()
{
IQueryable<T> query = this.Context.Set<T>();
return await query.Select(e => e).ToListAsync();
}
public class Program
{
static void Main(string[] args)
{
DB dB = new DB();
IUnitOfWork unitOfWork = new UnitOfWork(dB);
Task<IEnumerable<User>> users = unitOfWork.UserRepository.FindAll();
users.Wait();
Console.WriteLine(users);
}
}
When I run my code I am getting:当我运行我的代码时,我得到:
System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[System.Collections.Generic.IEnumerable'1[PasteBook.WebApi.Models.User],PasteBook.WebApi.Repositories.GenericRepository'1+d__5[PasteBook.WebApi.Models.User]]
System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[System.Collections.Generic.IEnumerable'1[PasteBook.WebApi.Models.User],PasteBook.WebApi.Repositories.GenericRepository'1+d__5[PasteBook.WebApi.Models 。用户]]
The simplest option is just to use an async entry point:最简单的选择就是使用异步入口点:
public class Program
{
// async Main method, with a Task return type
static async Task Main(string[] args)
{
DB dB = new DB();
IUnitOfWork unitOfWork = new UnitOfWork(dB);
// It's fine to await within the async method
var users = await unitOfWork.UserRepository.FindAll();
foreach (var user in users)
{
Console.WriteLine(user);
}
}
}
(Note that this answer doesn't try to address whether you should be using this particular database access pattern - it's focused on "how to use await from a console app.) (请注意,这个答案并没有试图解决您是否应该使用这种特定的数据库访问模式 - 它专注于“如何从控制台应用程序使用等待。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.