我有以下代码部分,其中SavePersonAsync方法正在调用3个外部方法,并且任何人都可以告诉我async / await方法的实现是否正确实现。是否没有正确实现async / await的任何调用链?
public PersonService(IPersonDbService personDbService,
IPersonEntityToPersonModelMapper personEntityToPersonModelMapper,
IPersonModelToPersonEntityMapper personModelToPersonEntityMapper)
{
_personDbService = personDbService;
_personEntityToPersonModelMapper = personEntityToPersonModelMapper;
_personModelToPersonEntityMapper = personModelToPersonEntityMapper;
}
public async Task<IEnumerable<PersonModel>> SavePersonAsync(IEnumerable<PersonModel> personsModel)
{
var personsEntity = await _personModelToPersonEntityMapper.MapPersonModelToPersonEntityAsync(personsModel);
var savedPersons = await _personDbService.SavePersonAsync(personsEntity.First()); // Currently only alow one person at a time, later it will allow to save a collection of persons
return await _personEntityToPersonModelMapper.MapPersonEntityToPersonModelyAsync(new List<PersonEntity>
{
savedPersons
});
}
}
public class PersonEntityToPersonModelMapper : IPersonEntityToPersonModelMapper
{
public async Task<IEnumerable<PersonModel>> MapPersonEntityToPersonModelyAsync(
IEnumerable<PersonEntity> personsEntity)
{
if (personsEntity.NullOrEmpty())
return await Task.FromResult(Enumerable.Empty<PersonModel>());
return await Task.FromResult(personsEntity.Select(personEntity => new PersonModel
{
FirstName = personEntity.FirstName,
LastName = personEntity.LastName
}));
}
}
public class PersonModelToPersonEntityMapper : IPersonModelToPersonEntityMapper
{
public async Task<IEnumerable<PersonEntity>> MapPersonModelToPersonEntityAsync(IEnumerable<PersonModel> personsModel)
{
if (personsModel.NullOrEmpty())
return await Task.FromResult(Enumerable.Empty<PersonEntity>());
return await Task.FromResult(personsModel.Select(personModel => new PersonEntity
{
FirstName = personModel.FirstName,
LastName = personModel.LastName
}));
}
}
答案 0 :(得分:-1)
从async await的定义中,当你编写等待时,流将开始顺序,因为你需要在下一个语句中使用输出,那么在你的情况下没有太多使用async await
要弄清楚它是如何运作的 假设你必须使用方法调用,它可以工作异步,你的代码就像:
Var a = GetMethodA();
Var b = GetMethodB();
等待a;
等待b;
在这种情况下,您的方法将异步工作