Search code examples
c#wpfcancellationcancellationtokensource

Cancel Parallel loop from form


I have a form in C# with a text box.

I want to run an event such that every time the text is changed in the textbox it cancels the last parallel.for loop and restarts with the new information, however I cannot work out how to retrieve the old cancellation token to cancel the previous iteration when this event was run.

I hope the code below explains what i want to do

private void Textbox_TextChanged(object sender, EventArgs e)
    {

       //call previous cancellation token from Textbox.tag and execute

        CancellationTokenSource cts = new CancellationTokenSource();
        ParallelOptions op = new ParallelOptions();
        op.CancellationToken = cts.Token;
        Parallel.For(0, 1, op, t =>
        {
            //Store cancellation token in textbox.tag

            //do stuff
        });
    }

Thanks in advance


Solution

  • You need to declare/store it outside of the method scope:

    private CancellationTokenSource cts = new CancellationTokenSource();
    private ParallelOptions op = new ParallelOptions();
    
    private void Textbox_TextChanged(object sender, EventArgs e)
        {
    
            //call previous cancellation token from Textbox.tag and execute
            cts.Cancel();
    
            cts = new CancellationTokenSource();
            op = new ParallelOptions();
    
            op.CancellationToken = cts.Token;
            Parallel.For(0, 1, op, t =>
            {
                //do stuff
            });
        }