C#如何编写一个用回调包装异步方法的协程? 统一

问题描述

我正在使用Unity Coroutines执行以下操作,但是我想这个问题通常适用于C#收益。

我有一个框架,可以将协程链接在一起。

IEnumerator ExecuteSequentially (IEmunerator[] coroutines); // this will execute the coroutines sequentially after each other

我正在使用一些第三方库,该库具有通过回调实现的异步方法(回调是通过反射执行的,该方法方法名称作为字符串加上要在其上调用回调的对象,以及将要调用的对象作为参数传递给回调)。

我想将对这些方法调用以及等待相应回调的操作包装到Coroutine中,以便将其与Coroutine链一起使用。

类似

HashSet<IEnumerator> outstandingAsyncCalls = new HashSet<IEnumerator>();

private IEnumerator YieldReturnNullWrapper() {
    yield return null;
}

public IEnumerator AsyncWrapper(arguments_to_asyncCall) {
    // IEnumerator thisIenumerator = YieldReturnNullWrapper();
    IEnumerator thisIenumerator = yield return null; // use Ienumerator generated by this method to identify the async call
    outstandingAsyncCalls.Add(thisIenumerator);
    somelib.asyncCall(arguments_to_asyncCall,/* callbackTarget */ this,/* callbackMethod */ "OnCallback",/* callbackMethodArgs */ thisIenumerator as Object);

    while (outstandingAsyncCalls.Contains(thisIenumerator)) {
        return thisIenumerator;
    }
}

void OnCallback(Object args) {
    outstandingAsyncCalls.Remove(args as IEnumerator);
}

但是我在error CS1002: ; expected上得到了IEnumerator thisIenumerator = yield return null; 如果我改用YieldReturnNullWrapper()包装方法,则会得到AsyncWrapper(...)': not all code paths return a value

我猜我可以使用AsyncWrapper的每次调用来创建一个新密钥(例如,通过计算一些静态int),而不是使用IEnumerator,但是由于返回的IEnumerator可以识别此协程,因此直接使用它会很好作为关键。我可以以某种方式在实际产生返回值之前生成IEnumerator返回值吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)