我有以下類別:與異步的流動困惑/等待功能
DataAccessFactory:
public class DataAccessFactory
{
public static IUserAccessLayer User() => new UserAccessLayer(new DataContext());
public static IAuthenticationAccessLayer Authentication() => new AuthenticationAccessLayer(new DataAccess.DataContext());
}
AuthenticationAccessLayer:
public class AuthenticationAccessLayer : IAuthenticationAccessLayer
{
private readonly DataContext context;
public AuthenticationAccessLayer(DataContext context)
{
this.context = context;
}
public async void RegisterAsync(UserRegisterModel model)
{
context.User.Add(new UserModel()
{
EmailAddress = model.Email,
PasswordHash = model.PasswordHash,
PasswordSalt = model.PasswordSalt
});
}
public async Task<bool> EmailExist(string email)
{
var user = await context.User.Where(x => x.EmailAddress.Equals(email)).FirstOrDefaultAsync();
if (user == null)
return false;
else
return true;
}
}
UserStore:
public class UserStore : ViewModelBase
{
public UserStore()
{
}
public UserStore(int userID)
{
this.UserID = userID;
}
#region Authentication
public async Task<bool> AuthenticateAsync(LoginModel model)
{
return await DataAccessFactory.Authentication().LoginAsync(model);
}
public async void RegisterUserAsync(UserRegisterModel model)
{
var store = DataAccessFactory.Authentication();
//check if unique email
if(await store.EmailExist(model.Email))
throw new ValidationException($"Email {model.Email} is already registered.");
store.RegisterAsync(model);
}
#endregion
}
我問題在於UserStore在RegisterUserAsync
函數中,UserRegisterModel
會在EmailExist
函數返回或拋出異常之前被添加到數據庫中?
'AuthenticationAccessLayer.RegisterAsync'實際上並不是'async'。 'context.User.Add'不會返回,也不會返回'Task' ... –
您還應該[避免異步無效方法](http://haacked.com/archive/2014/11/11/async -void-methods /) – stuartd