\$\begingroup\$
\$\endgroup\$
I want to wait for a line to be read, but only for so long before timing out. This is what I came up with. Is there a better way to do it?
Dim reader As New System.IO.StreamReader(pipe)
Dim nextCommand = Await New Func(Of Task(Of String))(
Function()
Dim t = reader.ReadLineAsync()
If (Not t.Wait(2000)) Then Throw New MyTimeoutExeption()
Return t
End Function).Invoke()
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
For operations that don't support cancellation themselves, You can combine Task.WhenAny() with Task.Delay():
Async Function TryAwait(Of T)(target As Task(Of T), delay as Integer) As Task(Of T)
Dim completed = Await Task.WhenAny(target, Task.Delay(delay))
If completed Is target Then
Return Await target
End If
Throw New TimeoutException()
End Function
Usage:
Dim nextCommand = Await TryAwait(reader.ReadLineAsync(), 2000)
answered Jan 18, 2015 at 0:55
svick
24.5k4 gold badges53 silver badges89 bronze badges
-
\$\begingroup\$ Can you please clarify one thing?
Return Await targetwon't actually continue to await, since it's already completed, right? Is its purpose there only to make sure aTask(Of T)is returned? \$\endgroup\$rory.ap– rory.ap2015年01月28日 14:11:54 +00:00Commented Jan 28, 2015 at 14:11 -
\$\begingroup\$ @roryap Yeah. And also to make sure exceptions from
targetare propagated. \$\endgroup\$svick– svick2015年01月28日 14:21:23 +00:00Commented Jan 28, 2015 at 14:21 -
\$\begingroup\$ What about Timeout? \$\endgroup\$John Demetriou– John Demetriou2018年06月04日 06:36:30 +00:00Commented Jun 4, 2018 at 6:36
You must log in to answer this question.
Explore related questions
See similar questions with these tags.
lang-vb