3

具有长时间运行方法的窗口商店应用程序,我需要在应用程序启动时调用它,但我不需要等待它完成。我希望它作为后台任务运行。如果转到应用程序的某个部分(报告),那么我将检查并在必要时等待该任务。

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

它是这样称呼的

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

它没有 Await 调用,我收到警告说它将同步运行。我如何开始这样的事情并让它异步运行?我希望它在自己的线程/任务上运行而不阻塞接口线程。有任何想法吗?

谢谢!

4

2 回答 2

11

你应该在你的函数中运行代码,Task然后你可以从中返回:

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

然后,您可以按照您的建议调用您的函数:

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

稍后您可以在需要结果时等待任务完成:

Dim result = Await updateTask
于 2013-02-15T06:01:39.103 回答
3

我认为这是一个更简单的解决方案,更容易阅读

Public Shared RunningTask As Task

Public Shared Sub CallingSub()
    'No need for sub to be async but can be async if needed for other reasons (see below)
    'but that doesn't stop the execution in the CallingSub
    'Get the task started... it's not going to wait for the task to be done just sets the task variable
    RunningTask = UpdateVehicleSummaries(0)

    'if a parameter comes from a function it may look like this
    'note that if you do this then the CallingSub would need the async keyword
    RunningTask = UpdateVehicleSummaries(Await FunctionReturnInt32())

    'Do stuff that does not require task to be done


End Sub
Public Shared Async Sub UseTaskResults()
    'Must be async so you can await the result
    Await RunningTask
    'Do stuff that requires task to be done
End Sub

Public Shared Function UpdateVehicleSummaries(p_vehicleID As Int32) As Task
    'No need for this function to be async since the function has no await
    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
End Function
于 2013-10-15T21:30:52.647 回答