无需等待即可启动任务

时间:2013-01-21 23:40:10

标签: vb.net windows-runtime windows-store-apps

我想在不使用Await关键字的情况下启动后台任务。相反,我想在各个点监视任务,并在必要时重新启动它以在后台更新信息。这是我试图调用的方法:

    Public 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
                Await UpdateVehicleStats(tempVehicle)
            End If
        Next

        Return True
    End Function

我尝试启动任务的代码似乎不起作用,我不确定如何提供参数。我收到错误“Task(Of Boolean)无法转换为System.Action和/或参数错误”

    Dim tempTask As Task
    tempTask = New Task(UpdateVehicleSummaries(tempVehicleID))
    tempTask.Start()

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

由于UpdateVehicleSummaries已经是异步的,你应该只做:

Dim tempTask As Task(Of Boolean) = UpdateVehicleSummaries(tempVehicleID)

返回的Task(Of T)将是“热门”(正在运行),但不应该阻止,因为Await调用将立即将控制流返回给调用者。


此方法的更典型用法是,如果您在运行时需要执行其他工作,则执行以下操作:

Dim tempTask = UpdateVehicleSummaries(tempVehicleID)

' Do your other work

Dim success = Await tempTask ' Get the boolean result asynchronously...

' use the result