调用并行协程,然后等待它们全部结束

问题描述 投票:1回答:2

我有一些协程:

IEnumerator a(){ /* code */ }
IEnumerator b(){ /* code */ }
IEnumerator c(){ /* code */ }

我想创建一个并行调用abc的协程,但是要等它们全部完成后再继续,就像这样:

IEnumerator d(){
    StartCoroutine(a());
    StartCoroutine(b());
    StartCoroutine(c());
    wait until all of them are over
    print("all over");
}

显然,我可以为每个协程使用一个布尔值来保存其当前状态,但是由于此方法不可扩展,因此我希望使用更简单的解决方案。

c# unity3d coroutine ienumerator
2个回答
1
投票

安装此package (source)时,可以将其实现为异步协程混合方法:

using System.Collections;
using System.Threading.Tasks;
using UnityEngine;

public class TestCoroutines : MonoBehaviour
{

    void Start () => D();

    IEnumerator A () { yield return new WaitForSeconds(1f); print($"A completed in {Time.time}s"); }
    IEnumerator B () { yield return new WaitForSeconds(2f); print($"B completed in {Time.time}s"); }
    IEnumerator C () { yield return new WaitForSeconds(3f); print($"C completed in {Time.time}s"); }

    async void D ()
    {
        Task a = Task.Run( async ()=> await A() );
        Task b = Task.Run( async ()=> await B() );
        Task c = Task.Run( async ()=> await C() );

        await Task.WhenAll( a , b , c );

        print($"D completed in {Time.time}s");
    }

}

控制台输出:

A completed in 1.006965s
B completed in 2.024616s
C completed in 3.003201s
D completed in 3.003201s

0
投票

您可以尝试Invoke(“ MethodName”,timeinFloat)并在每个方法中添加一个counter(int)/ bool。当它们全部完成运行后,根据计数器/布尔条件,您可以继续执行。

© www.soinside.com 2019 - 2024. All rights reserved.