gpt4 book ai didi

c# - 如何在 C# 中等待多个可能未初始化的任务?

转载 作者:行者123 更新时间:2023-12-02 16:20:50 25 4
gpt4 key购买 nike

我有一个创建资源的 API POST 端点,该资源可能有多个关系。为确保首先使用有效关系创建资源,我需要检查给定的 ID 是否存在。有多个这样的关系,我不想依次等待每个。这是我的代码:

[HttpPost]
public async Task<ActionResult<Person>> PostPerson(Person person)
{
ValueTask<Person> master, apprentice;
ValueTask<Planet> planet;
ValueTask<Models.LifeFormType> lifeFormType;
if (person.MasterId.HasValue)
{
master = _context.People.FindAsync(person.MasterId);
}


if (person.ApprenticeId.HasValue)
{
apprentice = _context.People.FindAsync(person.ApprenticeId);
}

if (person.FromPlanetId.HasValue)
{
planet = _context.Planets.FindAsync(person.FromPlanetId);
}

if (person.LFTypeId.HasValue)
{
lifeFormType = _context.LifeFormTypes.FindAsync(person.LFTypeId);
}
List<ValueTask> tasks = new List<ValueTask> {master, apprentice, planet, lifeFormType};

// if the above worked I'd process the tasks as they completed and throw errors
// if the given id was not found and such

_context.Attach(person);
// _context.People.Add(person);
await _context.SaveChangesAsync();

return CreatedAtAction("GetPerson", new { id = person.Id }, person);
}

如图here我想等待 [master,apprentice,planet,lifeFormType] 的列表当它们完成时,但我在创建 Local variable 'master' might not be initialized before accessing 列表的过程中遇到错误.因此,我尝试在每次检查资源是否具有创建 else 的值时尝试阻止并以某种方式添加 ValueTask.CompletedTask像这样:

if (person.MasterId.HasValue)
{
master = _context.People.FindAsync(person.MasterId);
}
else
{
master = ValueTask.CompletedTask;
}

但随后我收到一个错误提示 Cannot convert source type 'System.Threading.Tasks.ValueTask' to target type 'System.Threading.Tasks.ValueTask<Models.Person>' .

如何做到这一点?我想我现在只是等待每一个请求。

最佳答案

您可以通过在声明站点初始化 master 来避免这种情况。

最简单的方法是使用 default 关键字。

ValueTask<Person> master = default;

关于c# - 如何在 C# 中等待多个可能未初始化的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65553168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com