Start Async Task without using Await in called method

Robert Beaubien picture Robert Beaubien · Feb 15, 2013 · Viewed 16.7k times · Source

Window store app that has a long running method that I need to call when the application starts up, but I don't need to wait on it to complete. I want it to run as a background task. If the go to a certain part of the application (reporting), then I will check and if necessary wait on the task.

Public Shared Async Function UpdateVehicleSummaries(p_vehicleID As Int32) As Task(Of Boolean)
    Dim tempVehicle As Koolsoft.MARS.BusinessObjects.Vehicle

    For Each tempVehicle In Vehicles
        If p_vehicleID = 0 Or p_vehicleID = tempVehicle.VehicleID Then
            UpdateVehicleStats(tempVehicle)
        End If
    Next

    Return True

End Function

It is called like this

Dim updateTask As Task(Of Boolean) = UpdateVehicleSummaries(0)

It has no Await call in it and I get the warning that it will run synchronously. How do I start something like this and have it run asynchronously? I want it to run on its own thread/task without blocking the interface thread. Any ideas?

Thanx!

Answer

Damir Arh picture Damir Arh · Feb 15, 2013

You should run the code in your function inside a Task which you can then return from it:

Public Shared Function UpdateVehicleSummaries(p_vehicleID As Int32) As Task(Of Boolean)

    Return Task.Factory.StartNew(Of Boolean)(
        Function()
            Dim tempVehicle As Koolsoft.MARS.BusinessObjects.Vehicle

            For Each tempVehicle In Vehicles
                If p_vehicleID = 0 Or p_vehicleID = tempVehicle.VehicleID Then
                    UpdateVehicleStats(tempVehicle)
                End If
            Next

            Return True
        End Function)

End Function

You can then call your function as you suggested:

Dim updateTask As Task(Of Boolean) = UpdateVehicleSummaries(0)

Later on you can await the task to complete when you need the result:

Dim result = Await updateTask