'C# Utilizing cancellation tokens for each Task created

I have a task method that generates temperature profiles in my MainWindow but is called in another form when the user inputs data for a lot (an item produced) into an oven and record temp every 30secs.

public static async Task genLotProfile(string lotno,string filename, string datch,CancellationToken token)

try
{
       //get temperature and do other stuff
       Tprofile temp = getLogData(datch); 
       
       //task delay
       while (!token.IsCancellationRequested)
      {
          //Task delay
          await Task.Delay(30000, token);
      }
}
catch (OperationCanceledException e)
{

}

My idea was to call this on an enter button function in the input form everytime a lot is entered.

private void EnterBtn_Click(object sender, RoutedEventArgs e)
{
   //do other stuff

   //Call generate temp profile
    string filename = MainWindow.getTempProfileName(MainWindow.datachannel, lotnoTBX.Text);
                
    CancellationToken token = source.Token;
                
    MainWindow.genLotProfile(lotnoTBX.Text, filename, MainWindow.datachannel, token);
}

I also have a separate cancel class

    class Cancel
    {
        CancellationTokenSource _source;

        public Cancel(CancellationTokenSource source)
        {
            _source = source;
        }

        public void cancelTask()
        {
            _source.Cancel();
        }
    }

The thing is I will have multiple tasks running in my condition and I want to kill specific tasks with Cancel class on another output form when the user takes out the lot from the oven, will the cancellation token kill all my tasks running if I do the following

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Cancel c = new Cancel(source); 
c.cancelTask();


Solution 1:[1]

you need to create new CancellationTokenSource for each task:

private async void EnterBtn_Click(object sender, RoutedEventArgs e)
{
   //do other stuff

   //Call generate temp profile
    string filename = MainWindow.getTempProfileName(MainWindow.datachannel, lotnoTBX.Text);

    using CancellationTokenSource source = new CancellationTokenSource();                
    CancellationToken token = source.Token;
                
    await MainWindow.genLotProfile(lotnoTBX.Text, filename, MainWindow.datachannel, token);
}

When cancelling a specific task, you just need to call cancel() the right instance of the token.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1