Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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()
share|improve this question

1 Answer 1

up vote 3 down vote accepted

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)
share|improve this answer
    
Can you please clarify one thing? Return Await target won't actually continue to await, since it's already completed, right? Is its purpose there only to make sure a Task(Of T) is returned? –  roryap Jan 28 at 14:11
    
@roryap Yeah. And also to make sure exceptions from target are propagated. –  svick Jan 28 at 14:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.