title: How do I deal without ByRef in an Async function?
body: <p>I'm working on replacing my old code that uses threads to a .NET 4.5 Task based system.</p>
  
  <p>I have the following sub that I wish to convert;</p>
  
  <pre><code>Public Function Delay(Milliseconds As Integer, ByRef Job As Job) As Boolean
     For i As Integer = 1 To CInt(Milliseconds / 100)
        Thread.Sleep(100)
        If Job.IsCancelled Then Return True
     Next
     Return False
  End Function
  </code></pre>
  
  <p>The Job class is one of my own, but importantly it contains an integer which is set to 1 if the job should be cancelled.  So, the Delay function allows me to put a thread to sleep for X milliseconds, but if the job is cancelled during that time it will stop sleeping and return True.</p>
  
  <p>I'm not sure how to do this with Await Task.Delay, here's my attempt;</p>
  
  <pre><code>  Public Async Function Delay(Milliseconds As Integer, Job As Job) As Tasks.Task(Of Boolean)
      For i As Integer = 1 To CInt(Milliseconds / 100)
        Await Tasks.Task.Delay(100)
        If Job.IsCancelled Then Return True
      Next
      Return False
    End Function
  </code></pre>
  
  <p>The problem I'm having is that Async methods don't allow me to use ByRef, which means it won't be able to detect when the Job has been cancelled.  Another issue is that await can't be used inside try/catch/finally or a synclock.  I was under the impression you can write asynchronous code that looks like synchronous code.  How can I get around these issues?</p>