您的问题是在异步部分还是在“获取和更新用户”部分?
“获取和更新用户”的部分如果不告诉我们您访问数据库的方法很难描述:您使用的是实体框架吗? SQL?
SQL、DbConnection、DbCommand
假设您已经有同步方法:
public User FetchUserById(int userId) {...}
private void UpdateExistingUser(User user) {...}
您必须创建类似的异步方法:
public Task<User> FetchUserByIdAsync(int userId);
private Task UpdateExistingUserAsync(User user);
如果您使用 SQL,您可能会使用类DbCommand 和方法ExecuteReader 和ExecuteNonQuery。对于您的异步方法,请使用类似的异步方法。
注意:要使用 DisposeAsync,您需要 C# 8。否则使用 try ... finally 并显式调用 DisposeAsync
private async dbConnection CreateFetchUserCommand(
DbConnection Connection,
int userId)
{
var dbCommand = connection.CreateCommand();
dbCommand.CommandText = ...
var dbParameter = dbCommand.CreateParameter();
... // etc.
return dbCommand;
}
private async DbCommand CreateUpdateUserCommand(DbConnection connection, User user)
{
var dbCommand = connection.CreateCommand();
dbCommand.CommandText = ...
var dbParameter = dbCommand.CreateParameter();
... // etc.
return dbCommand;
}
public Task<User> FetchUserByIdAsync(int userId)
{
using (var dbConnection = new DbConnection(...))
{
await dbConnection.OpenAsync();
using (var dbCommand = dbConnection.CreateFetchUserCommand(dbConnection, userId))
{
using (var dataReader = await dbCommand.ExecuteReaderAsync())
{
// use async methods to access fetched data
User user = await ...
return user;
}
}
}
}
类似地:添加一个类似于您现有的 UpdateUser 的 UpdateExistingUserAsync。
public UpdateUser(User user)
{
// TODO: exception if user null
User existingUser = await FetchUserById(user.Id);
if (existingUser == null)
{
// user does not exist
}
else
{
... // copy values from user to existingUser
await UpdateExistingUserAsync(existingUser);
}
}
从用户复制到现有用户可以只更新您提供的值。如果您总是想更新完整的用户,则不需要 FetchUserById。
实体框架
using (var dbConext = new MyDbContext(...))
{
User existingUser = await dbConnection.Users.FindAsync(user.Id)
if (existingUser != null)
{
... // copy values from user to existingUser
await dbContext.SaveAsync();
}