在联合中使用UniRx包时,可以使用异步等待。但是,转换如下内容的正确方法是什么(这个示例使用一个GPT-3www请求,但它可以是任何东西)
string result1 = await textAI.GetCompletion("Albeit Einstein was");
string result2 = await textAI.GetCompletion("Susan Sarandon is");对于同时启动GetCompletion函数的东西,然后当它们全部完成并返回其结果时继续吗?例如使用伪代码,如下所示:
string result1 = null;
string result2 = null;
await Task.WhenAll({
result1 = await textAI.GetCompletion("Albeit Einstein was"),
result2 = await textAI.GetCompletion("Susan Sarandon is")
});
Debug.Log("Results: " + result1 + ", " + result2);谢谢!
发布于 2022-10-25 11:36:05
您可以使用现有的Task.WhenAll
async void Start()
{
Task<string> a = AsyncRoutineA(); // Here no await, you want the Task object
Task<string> b = AsyncRoutineB();
await Task.WhenAll(a, b); // add all tasks and await that one
Debug.Log(a.Result + " " + b.Result);
}
async Task<string> AsyncRoutineA()
{
await Task.Delay(1000);
return "A Done";
}
async Task<string> AsyncRoutineB()
{
await Task.Delay(2000);
return "B Done";
}UniRx也会这样做,增加额外的开销,这样您就可以得到一个在这个上下文中不使用的可观察对象。
你也可以用协同线做同样的事情:
IEnumerator Start()
{
string resultA = null;
string resultB = null;
StartCoroutine(AsyncRoutineA((result) => resultA = result));
StartCoroutine(AsyncRoutineA((result) => resultB = result));
yield return new WaitUntil(()=>
{
return !string.IsNullOrEmpty(resultA) && !string.IsNullOrEmpty(resultB);
});
Debug.Log(resultA + " " + resultB);
}
IEnumerator AsyncRoutineA(Action<string> result)
{
yield return new WaitForSeconds(1);
result.Invoke("A done");
}
IEnumerator AsyncRoutineB(Action<string> result)
{
yield return new WaitForSeconds(2f);
result.Invoke("B done");
}https://stackoverflow.com/questions/74192498
复制相似问题