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 に答える