Why does this function fail #288
Replies: 3 comments 6 replies
|
First I would recommend not using "Async Sub" which is the VB equivalent of async void antipattern. Such methods cannot be awaited and might cause errors that will not be catched. Also, I think the code looks strange but I guess you are using Anyhow, I guess this is too complex to pin this down remotely. |
|
I feared threading issues, but there were none, nevertheless, I changed code, to make it into a Async Function. Yes |
|
@vijaysridhara The behavior here is actually explained by the button click handler rather than You're creating the task: Dim t As Task(Of Boolean)
t = SendMessage(txtRequest.Text.Trim())but never awaiting it. While calling an async method does start executing it, the caller immediately returns and any exceptions or completion are no longer observed. Microsoft explicitly recommends awaiting For a WinForms event handler, the usual pattern is: Private Async Sub butSend_Click(sender As Object, e As EventArgs) Handles butSend.Click
Await SendMessage(txtRequest.Text.Trim())
End Suband keep: Private Async Function SendMessage(msg As String) As Task(Of Boolean)
...
End FunctionThis ensures the async operation is awaited, exceptions propagate correctly, and the UI remains responsive. Microsoft also recommends using If, on the other hand, you intentionally don't want to wait for the operation, then it's better to make that explicit using a fire-and-forget helper (such as If this solves your problem, feel free to mark it as the accepted answer so others can find it easily. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi,
Can some one help, why does this function fail? The call jumps to directly "Finally" block without waiting for response. I tried chat.SendAsync also, the same result.
` Private Async Sub SendMessage(msg As String)
End Sub`
All reactions