0
votes

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

Private Sub Button_Start_Click(sender As Object, e As EventArgs) Handles 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

1
Please post your code not as an image. It is really difficult to read, and SO has a syntax highlighting feature... - Martin Verjans
Thanks, I've corrected. - Alberto Deidda

1 Answers

1
votes

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. You could probably write it as a lamda function though. To cancel the task, simply call cancelSource.cancel from you cancel button handler.

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. If you don't do this, and you attempt to update the GUI in some way, you'll get errors.

We start by creating a task that returns an array of doubles by running the gensin function. 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