我正在编写一个将数据传输到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循环?
有人能澄清我看到的行为吗?
发布于 2013-03-01 11:10:28
避免使用async void
。让你的方法返回Task
而不是void
。然后你就可以await
它们了。
如下所示:
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();
}
发布于 2017-06-16 08:14:30
等待AsynMethod完成任务的最佳解决方案是
var result = Task.Run(async() => await yourAsyncMethod()).Result;
发布于 2019-12-14 16:07:32
只需让Wait()等待,直到任务完成
GetInputReportViaInterruptTransfer().Wait();
https://stackoverflow.com/questions/15149811
复制相似问题