简体   繁体   English

Visual Basic异步任务而不是同步任务

[英]Visual Basic Async Task instead Sync Task

I have a function that performs a synchronous task, I would do the same but with an asynchronous task. 我有一个执行同步任务的函数,但会执行异步任务。

How should i do ? 我应该怎么做 ?

This is the code: 这是代码:

Public Class Form1 Private taskOUT As Task 公共类Form1私人任务作为任务输出

Private Sub Button_Start_Click(sender As Object, e As EventArgs) Handles Button_Start.Click 私有子Button_Start_Click(作为对象发送,作为EventArgs发送)处理Button_Start.Click

    Dim freq As Double = TextBox1.Text
    Dim Amp As Double = TextBox2.Text
    Dim SPB As Double = TextBox3.Text
    Dim CPB As Double = TextBox4.Text
    '---------------------------------------
    Dim SCRate As Double = (freq * SPB) / CPB
    '---------------------------------------
    taskOUT = New Task()  'Crea un task
    taskOUT.AOChannels.CreateVoltageChannel("Dev1/ao0", "", -10, 10, AOVoltageUnits.Volts) 'Aggiunge un canale in Out
    taskOUT.Timing.SampleClockRate = SCRate
    taskOUT.Timing.ConfigureSampleClock("", SCRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000)
    '-----------------------------
    Dim ydata As Double()
    ydata = GenSin(freq, Amp, SCRate, SPB)
    '-------------------------------------------
    Dim writer As New AnalogSingleChannelWriter(taskOUT.Stream)
    writer.WriteMultiSample(False, ydata)
    taskOUT.Start()
End Sub
'-----------------------------------------------------------------------
Public Shared Function GenSin( _
    ByVal freq As Double, _
    ByVal amp As Double, _
    ByVal sampleClockRate As Double, _
    ByVal samplePerBuffer As Double) As Double()

    Dim dt As Double
    Dim IntSample As Integer

    dt = 1 / sampleClockRate
    IntSample = CInt(SamplePerBuffer) - 1
    Dim y(IntSample - 1) As Double
    For i As Integer = 0 To IntSample - 1
        y(i) = amp * Math.Sin((2.0 * Math.PI) * freq * (i * dt))
    Next
    Return y
End Function

Private Sub Button_Stop_Click(sender As Object, e As EventArgs) Handles Button_Stop.Click
    taskOUT.Stop()
    taskOUT.Dispose()
End Sub

End Class 末级

Something like this should do it: 这样的事情应该做到:

Private cancelSource As CancellationTokenSource

Sub StartWork
        cancelSource = New CancellationTokenSource
        Dim uiSyncContext = Tasks.TaskScheduler.FromCurrentSynchronizationContext
        Dim task = New Tasks.Task(Of Double())(Function() GenSin(3.4, 1.2, 100.0, 1000.0, cancelSource.Token))
        task.ContinueWith(Sub(dt) WriteData(dt.result), 
                          cancelToken, 
                          Tasks.TaskContinuationOptions.OnlyOnRanToCompletion, 
                          uiSyncContext)
    End Sub

    Function GenSin(freq As Double, amp As Double, rate As Double, spb As Double, cancelToken As CancellationToken) As Double()
        Dim dt As Double
        Dim isamp As Integer
        dt = 1 / rate
        isamp = CInt(spb) - 1
        Dim y(isamp - 1) As Double
        For i As Integer = 0 To isamp - 1
            If cancelToken.IsCancellationRequested Then Return Nothing
            y(i) = amp * Math.Sin(2 * Math.PI * freq * i * dt)
        Next
        Return y
    End Function

    Sub WriteData(results As Double()) 
        ' This is where you output the data
    End Sub

I've split WriteData to a separate function, as I don't have you libraries. 我将WriteData拆分为一个单独的函数,因为我没有库。 You could probably write it as a lamda function though. 您可能可以将其编写为lamda函数。 To cancel the task, simply call cancelSource.cancel from you cancel button handler. 要取消任务,只需从取消按钮处理程序中调用cancelSource.cancel。

The uiSyncContext may not be needed - it simply makes sure that when your task completes then the next step in the pipeline will run on the UI thread. 可能不需要uiSyncContext-它只是确保任务完成时,管道中的下一步将在UI线程上运行。 If you don't do this, and you attempt to update the GUI in some way, you'll get errors. 如果不这样做,并且尝试以某种方式更新GUI,则会出现错误。

We start by creating a task that returns an array of doubles by running the gensin function. 我们首先创建一个任务,通过运行gensin函数返回一个双精度数组。 We then append a continuation task that writes the output. 然后,我们附加一个写入输出的继续任务。 The continuation task only runs if the first task completed okay. 仅当第一个任务完成时,继续任务才会运行。 If you cancelled it, or it threw an error, this would not run. 如果您取消了它,或者它抛出了错误,它将无法运行。 You can chain a whole bunch of tasks together this way, with distinct routing for the success/fail/cancel outcomes 您可以通过这种方式将一堆任务链接在一起,并为成功/失败/取消结果提供独特的路由

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM