且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待异步方法完成?

更新时间:2022-04-12 21:49:18

避免 async void.让您的方法返回 Task 而不是 void.然后你可以await他们.

Avoid async void. Have your methods return Task instead of void. Then you can await them.

像这样:

private async Task RequestToSendOutputReport(List<byte[]> byteArrays)
{
    foreach (byte[] b in byteArrays)
    {
        while (condition)
        {
            // we'll typically execute this code many times until the condition is no longer met
            Task t = SendOutputReportViaInterruptTransfer();
            await t;
        }

        // read some data from device; we need to wait for this to return
        await RequestToGetInputReport();
    }
}

private async Task RequestToGetInputReport()
{
    // lots of code prior to this
    int bytesRead = await GetInputReportViaInterruptTransfer();
}