【发布时间】:2022-01-19 03:05:40
【问题描述】:
我正在尝试实现一个等待integer 返回值更新的串行端口接口。出于学习目的,我有一个 Async 函数从具有随机时间延迟的过程函数返回一个 integer。我包括了我在 cmets 中看到的错误。该函数似乎没有返回Integer,也没有GetAwaiter。
Private Sub btnSubMain_Click(sender As Object, e As EventArgs) Handles btnSubMain.Click
Dim Answer As Integer
Answer = SomeInteger() 'Value of type 'Task(of Integer)' cannot be converted to 'Integer'
End Sub
Public Async Function SomeInteger() As Task(Of Integer)
Dim exampleInteger As Integer = Await AwaitedprocessAsync() 'Await requires that type 'Integer"
' have a suitable GetAwaiter method
Return exampleInteger
End Function
Function AwaitedprocessAsync() As Integer
Dim timeout As Integer = CInt(Rnd() * 100)
Thread.Sleep(timeout)
Return 34 'return some test integer
End Function
【问题讨论】:
-
您的
AwaitedprocessAsync方法需要返回Task才能等待。另外,请考虑使用Await Task.Delay(timeout)而不是Thread.Sleep(timeout)。 -
@RelicCoder - SerialPort 有一个在收到数据时触发的事件,所以我不明白你为什么这样做。
标签: vb.net asynchronous async-await task-parallel-library