窗口存储应用程序,它有一个长时间运行的方法,我需要在应用程序启动时调用,但我不需要等待它完成。我希望它作为后台任务运行。如果转到应用程序的某个部分(报告),那么我将检查并在必要时等待该任务。
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调用,我得到它将同步运行的警告。我如何启动这样的东西并让它以异步方式运行?我希望它在自己的线程/任务上运行而不会阻塞接口线程。有什么想法吗?
感谢名单!
答案 0 :(得分: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
答案 1 :(得分:2)
我认为这是一个更容易阅读的更简单的解决方案
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