首页 > 解决方案 > Unity3D 中的 Awaiter 实现有什么问题?

问题描述

所以我试图制作一个简单的等待结构,允许我返回一个布尔值:

// define a special container for returning results
public struct BoolResult {
    public bool Value;
    public BoolAwaiter GetAwaiter () {
        return new BoolAwaiter(Value);
    }
}

// make the interface task-like
public readonly struct BoolAwaiter : INotifyCompletion {
    private readonly bool _Input;

    // wrap the async operation
    public BoolAwaiter (bool value) {
        _Input = value;
    }

    // is task already done (yes)
    public bool IsCompleted {
        get { return true; }
    }

    // wait until task is done (never called)
    public void OnCompleted (Action continuation) => continuation?.Invoke();

    // return the result
    public bool GetResult () {
        return _Input;
    }
}

我像这样使用它:

private async BoolResult LoadAssets (string label) {
    //
    // some await asyncFunction here
    //

    // then at the end
    return new BoolResult { Value = true };
}

但我仍然得到这个编译错误:

error CS1983: The return type of an async method must be void, Task or Task<T>

我以为我BoolResult的已经是 Task-like 了?这里有什么问题?

标签: c#unity3dasync-awaittask

解决方案


推荐阅读