HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Wait for System.IO.StreamReader.ReadLineAsync

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
waitsystemforstreamreaderreadlineasync

Problem

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()

Solution

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)

Code Snippets

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
Dim nextCommand = Await TryAwait(reader.ReadLineAsync(), 2000)

Context

StackExchange Code Review Q#77710, answer score: 5

Revisions (0)

No revisions yet.