Search code examples
c#multithreadingtasktoken

Stop Tasks with token used in an array of tasks


I have this example:

var asyncTasks = new Task[list.Length];
for (int i = 0; i< list.Length; i++)
{
    asyncTasks[i] = tf(cts.Token, list[i]);                
}
await Task.WhenAll(asyncTasks);
//do other stuffs when all tasks completed

and of course i have my async function called tf:

private async Task tf(CancellationToken token , string list)
{
        try
        {
            await Task.Run(() =>
            {
                if (token.IsCancellationRequested)
                {
                    MessageBox.Show("Stopped", "Operation Aborted");
                    token.ThrowIfCancellationRequested();
                    cts = new CancellationTokenSource();
                } 
                // do something
            }, token);
       }catch{}
       cts = new CancellationTokenSource();
}

EDIT: in my cancel button i declare: cts.Cancel();

This method works properly for me because it executes an array of tasks at the same time, but in my opinion I'm not able to send token for cancellation request because all cts.Token already assigned are valid, so if in another button i try to cts.Cancel() this won't work. How can i do the same but making cancellation token request valid?


Solution

  • The problem was that i reset the token for every call with cts = new CancellationTokenSource(); at the end of task function

    Function fixed:

    private async Task tf(CancellationToken token , string list)
    {
            try
            {
                await Task.Run(() =>
                {
                    if (token.IsCancellationRequested)
                    {
                        MessageBox.Show("Stopped", "Operation Aborted");
                        token.ThrowIfCancellationRequested();
                        cts = new CancellationTokenSource();
                    } 
                    // do something
                }, token);
           }catch{}
    }