如何等待异步委托

Uri*_*iil 31 .net c# asynchronous async-await

在其中一个MVA视频中,我看到了下一个结构:

static void Main(string[] args)
{
    Action testAction = async () =>
    {
        Console.WriteLine("In");
        await Task.Delay(100);
        Console.WriteLine("After first delay");
        await Task.Delay(100);
        Console.WriteLine("After second delay");
    };

    testAction.Invoke();
}
Run Code Online (Sandbox Code Playgroud)

执行结果将是:

In
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

它是完美的编译,但现在我没有看到任何方式等待它.我可能会在调用之后Thread.SleepConsole.ReadKey之后,但这不是我想要的.

那么应该如何修改这个代表以使其变得等待?(或者至少我如何跟踪该执行是否完成?)

这些代表有实际用途吗?

Yuv*_*kov 49

为了等待某事,它必须是等待的.事实void并非如此,你无法等待任何Action代表.

等待是任何实现GetAwaiter方法的类型,它返回一个实现INotifyCompletion或者ICriticalNotifyCompletion,例如Task和类型的类型Task<T>.

如果要等待委托,请使用Func<Task>,这与具有以下签名的命名方法等效:

public Task Func()
Run Code Online (Sandbox Code Playgroud)

因此,为了等待,请将您的方法更改为:

static void Main(string[] args)
{
    Func<Task> testFunc = async () =>
    {
        Console.WriteLine("In");
        await Task.Delay(100);
        Console.WriteLine("First delay");
        await Task.Delay(100);
        Console.WriteLine("Second delay");
    };
}
Run Code Online (Sandbox Code Playgroud)

现在你可以等待它:

await testFunc();
Run Code Online (Sandbox Code Playgroud)