我正在编写一个WinForms应用程序,用于向USB HID类设备传输数据。我的应用程序使用优秀的通用HID库v6.0,可以在这里找到。简而言之,当我需要向设备写入数据时,会调用以下代码:
很遗憾,我对.NET 4.5中的新异步/等待技术不太熟悉。之前我读了一些await关键字的内容,这让我觉得在RequestToGetInputReport()内部调用GetInputReportViaInterruptTransfer()函数会等待(也许是这样?),但似乎RequestToGetInputReport()函数本身并没有等待,因为我几乎立即重新进入while循环。有人能澄清我看到的行为吗?
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循环。有人能澄清我看到的行为吗?
await
称为“异步等待”(asynchronous wait)是有帮助的,因为它可以阻塞方法(如果必要),但不会阻塞线程。因此,即使它不是阻塞等待,我们也可以说RequestToSendOutputReport
在“等待”RequestToGetInputReport
。 - Stephen ClearyResult
属性和Wait()
方法,如果它们因死锁而不能使用呢? - David Klempfnerawait
出现之前,Wait
和Result
已经存在于Task
类型中。在await
到来之前,Task
是任务并行库的一部分,主要用于并行编程。 - Stephen Cleary