How to cancel a long-running async task in a C # Winforms application

I am a rather inexperienced C # programmer and need help managing the flow of my program. This is WinFormApp, which requests several user inputs and then uses them to establish serial communication with the device for taking measurements. Measurements are made in an asynchronous method, which takes about 20 minutes. Therefore i use

    void main()
    {
        //Setup
    }

    private void button1_Click(object sender, EventArgs e)
    {
        await measurements();
        //Plot results
    }

    private async Task measurements()
    {
        while(true){
        //Make some measurements
        await Task.Delay(120000);
        //Make measurements, present data in the UI form.
        //return if done
        }
    }

Now I need to make a button that allows the user to cancel the measurement, to change any input or parameter, and then restart the measurement. So I added a Cancel button.

    private void button7_Click(object sender, EventArgs e)
    {
        textBox64.Enabled = true;
        button6.Enabled = true;
        button5.Enabled = true;
        textBox63.Enabled = true;
        button3.Enabled = true;
        trackBar1.Enabled = true;
        timer.Enabled = true;
        button7.Enabled = false;
        clearData();
        // measurement.Stop();            
    }

, . try-catch button1_Click() button7_Click, button1_Click().
measurements() . 70- UI .
, .

, , , , Goto.

+4
2

, CancellationTokenSource async.

Microsoft, , . :

CancellationToken. , . , :

  • CancellationTokenSource.
  • API CancellationToken from CancellationTokenSource (CancellationTokenSource.Token).
  • CancellationTokenSource object (CancellationTokenSource.Cancel()).
  • , CancellationToken.ThrowIfCancellationRequested.

, , .

+4

, .

CancellationToken. .

CancellationTokenSource cts;

private async button1_Click(object sender, EventArgs e)
{
    toggleAsyncTask(false)
}

private void toggleAsyncTask(bool isCancelled)
{
    if(cts==null)
        var cts = new CancellationTokenSource();
    if(!isCancelled)
    {
        await measurements(cts.Token);
    }
    else
    {
        cts.Cancel();
        cts.Dispose();
        cts = null;
    }
}

private async Task measurementsOne(CancellationToken token)
{
    try
    {
        while(true){
            //Make some measurements
            await Task.Delay(120000); // don't know if you need this.
            //Make measurements, present data in the UI form.
            //return if done
    }
    catch(OperationCancelledException)
    {
        // to do if you please.
    }
}

private void button7_Click(object sender, EventArgs e)
{
    // button stuff
    toggleAsyncTask(true); // isCancelled is true.          
}
+2

Source: https://habr.com/ru/post/1626341/


All Articles