I'm working on replacing my old code that uses threads to a .NET 4.5 Task based system.
I have the following sub that I wish to convert;
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
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.
I'm not sure how to do this with Await Task.Delay, here's my attempt;
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
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?