首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何等待异步方法完成?

如何等待异步方法完成?
EN

Stack Overflow用户
提问于 2013-03-01 11:07:07
回答 6查看 372.5K关注 0票数 163

我正在编写一个将数据传输到USB类设备的WinForms应用程序。我的应用程序使用了优秀的通用HID库v6.0,它可以在here中找到。简而言之,当我需要向设备写入数据时,会调用以下代码:

private async void 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
        RequestToGetInputReport();
    }
}

当我的代码退出while循环时,我需要从设备中读取一些数据。但是,设备不能立即响应,因此我需要等待此调用返回,然后才能继续。因为它当前存在,所以RequestToGetInputReport()声明如下:

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

无论如何,GetInputReportViaInterruptTransfer()的声明看起来像这样:

internal async Task<int> GetInputReportViaInterruptTransfer()

不幸的是,我对.NET 4.5中新的异步/等待技术的工作原理不是很熟悉。我之前读过一些关于await关键字的文章,这给我的印象是RequestToGetInputReport()内部对GetInputReportViaInterruptTransfer()的调用将会等待(也许它是等待的?)但似乎对RequestToGetInputReport()的调用本身并没有等待,因为我似乎几乎是立即重新进入while循环?

有人能澄清我看到的行为吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15149811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档