如何在 c# 中定义异步操作?

3

我真的想知道是否有一种定义动作变量async的方法?或者有其他替代方法吗?

public System.Action myAction;

public async System.Action myAsyncAction;
void Start()
{
    // normal action
    myAction += () =>
    {
        Debug.Log("Inject some code in runtime..");
    };

    // I want something like this that support wait time..
    myAsyncAction += () =>
    {
        await Task.Delay(2000f);
        
        Debug.Log("Inject some code in runtime..");
    };
}

1
但是,Action 用于 void,而可等待的对象(awaitables)如果没有结果值,则返回类似于 Task 的东西,如果有结果值,则返回 Task<T>。在任一情况下,Task 是返回值,因此它们不是 void(不是 Action)。不要试图等待 void ;) - Caius Jard
克林顿提到的那个问题已经被解决了。实际上,我一直在寻找一种在运行时向程序体添加代码的方法。谢谢大家。:)) - KiynL
1个回答

6

我以前用过 Func<Task>。例如:

Func<Task> asyncMethod = async () =>
{
    await Task.Delay(1000);
    Console.WriteLine("done here");
};

await asyncMethod();

1
可能有比“..Action”更好的后缀。 - Caius Jard
好的,@CaiusJard,已更改为asyncMethod - Clinton
asyncActionasyncMethod之间,我更喜欢前者。 :-) - Theodor Zoulias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接