r3p*_*ica 11 c# asynchronous entity-framework
我的服务中有这个方法:
public virtual async Task<User> FindByIdAsync(string userId)
{
this.ThrowIfDisposed();
if (userId == null)
{
throw new ArgumentNullException("userId");
}
return await this.repository.FindByIdAsync(userId);
}
Run Code Online (Sandbox Code Playgroud)
然后在视图中我有这个代码:
using (var service = new UserService(new CompanyService(), User.Identity.GetUserId()))
{
var user = service.FindByIdAsync(id);
}
Run Code Online (Sandbox Code Playgroud)
但用户是任务而不是用户.我尝试添加等待服务调用,但除非当前方法是异步,否则我不能使用await.如何访问User类?
Ily*_*huk 10
this在async没有特殊螺纹锁定对象的方法中使用是危险的如果您无法使用await,请使用以下代码.
Task<User> task = TaskFindByIdAsync();
task.Wait(); //Blocks thread and waits until task is completed
User resultUser = task.Result;
Run Code Online (Sandbox Code Playgroud)