签名异步。和同步方法

时间:2017-07-08 23:12:56

标签: vb.net asynchronous async-await signature

如果我有一个方法Sub Foo(fooParam as String),我想编写像

这样的异步版本
 Function FooAsync (fooParam as String) as Task
     Return Task.Run(Sub() Foo(fooParam))
 End Function

现在我需要进度和取消,所以我需要将签名更改为

Function FooAsync (fooParam as String, progress as IProgress(of String), cancellationToken as CancellationToken) as Task
     Return Task.Run(Sub() Foo(fooParam))
 End Function

微软称异步版本应该与同步版本具有相同的签名,那么这里最好的做法是什么,或者我理解错了?

将进度和cancelToken传递给同步。方法对我来说似乎毫无意义......但只有这样我才能将同步包裹起来。方法并将其作为任务返回。

为了更好地理解代码,关于我现在如何做。在Async中刚刚编写了同步方法,添加了进度和取消调用。但我确定这不是我应该这样做的方式:

Public Sub DoCalibration(calibrationHoldTimeForReading As Integer)
    If Not PressureCalibrator.SerialPort.IsOpen() Then
        PressureCalibrator.SerialPort.Open()
    End If
    PressureCalibrator.PressureUnit = PressureUnit.bar
    For Each point In InputList
        SetMessPointAndMeasure(point, calibrationHoldTimeForReading)
    Next
    PressureCalibrator.Vent()
    PressureCalibrator.SerialPort.Close()
    Log.WriteLog("Calibration completed.")
End Sub


Public Function DoCalibrationAsync(calibrationHoldTimeForReading As Integer, Optional progress As IProgress(Of CalibrationStepResult) = Nothing, Optional cancellationToken As CancellationToken = Nothing) As Task 
     Return Task.Run((Sub()
                        If Not PressureCalibrator.SerialPort.IsOpen() Then
                            PressureCalibrator.SerialPort.Open()
                        End If
                        PressureCalibrator.PressureUnit = PressureUnit.bar
                        For Each point In InputList
                            Dim measureResult = SetMessPointAndMeasure(point, calibrationHoldTimeForReading)
                            If Not IsNothing(cancellationToken) Then  
                            CancellationToken.ThrowIfCancellationRequested()
                            End If
                            If Not IsNothing(progress) Then
                                progress.Report(measureResult)
                            End If
                        Next
                        PressureCalibrator.Vent()
                        PressureCalibrator.SerialPort.Close()
                        Log.WriteLog("Calibration completed.")
                    End Sub), cancellationToken)
End Function

1 个答案:

答案 0 :(得分:0)

感谢@PauloMorgado,我通过阅读他发布的文章和其他与之相关的文章了解了这些指南。