Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Running Function from Task.Run with Cancellation Token gives infinite loop

Running Function from Task.Run with Cancellation Token gives infinite loop

Scheduled Pinned Locked Moved C#
learning
7 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • E Offline
    E Offline
    Exoskeletor
    wrote on last edited by
    #1

    I have this function

    private async Task SearchForAllNumbers(int num = -1)
    {
    if (num == -1)
    DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle), GetString(Resource.String.Common_SearchMessage));
    dates = DateFunctions.GetSelectedDates(DateFrom, DateTo);

            var list = string.Empty;
            var klirwseis = ", Κληρωσεις: ";
            if (num == -1)
                list = ListTextView.Text;
            else
                list = num.ToString();
            var nums = list.Split(',').Select(Int32.Parse).ToList();
            if (seperateCheckBox.Checked)
            {
                DisplayLoadingMessage(false);
                seperateCheckBox.Checked = false;
                for (int k = 0; k < nums.Count; k++)
                {
                    await SearchForAllNumbers(nums\[k\]);
                }
                return -1;
            }
            var totalCoutner = 0;
            for (int datesPos = 0; datesPos <= dates.Count; datesPos++)
            {
               ... Do some calculations
                }
                HistoryTextView.Text = "Ημερομηνία: " + dates\[datesPos\] + ", Λίστα: " + list + ", Κληρώθηκε: " + totalCoutner + " φορές" + HistoryTextView.Text;
                if (showListsCheckBox.Checked)
                    HistoryTextView.Text = klirwseis + HistoryTextView.Text;
            }
            DisplayLoadingMessage(false);
            HistoryTextView.Text = ".\\n" + HistoryTextView.Text;
            return totalCoutner;
            return 0;
        }
    

    And i want to be able to cancel it when its running so i have created this function

    private async Task SearchFoNumbersAsync()
    {
    ActiveCancellationTokenSource = new CancellationTokenSource();
    DrawResultsTypeEnum searchType = (DrawResultsTypeEnum)ShowResultsSpinnerPosition;

            var task = Task.Run(async () =>
            {
                if (searchType == DrawResultsTypeEnum.AllNumbers)
                    await SearchForAllNumbers();
                else if (searchType == DrawResultsTypeEnum.AnyWinningCombination)
                    await SearchAnyWinningCombination();
                SaveHistory();
            }, ActiveCancellationTokenSource.Token); // Pass same token to Task.Run.
    
            try
            {
                await task;
            }
            catch (System.OperationCanceledException e)
            {
    
    L 1 Reply Last reply
    0
    • E Exoskeletor

      I have this function

      private async Task SearchForAllNumbers(int num = -1)
      {
      if (num == -1)
      DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle), GetString(Resource.String.Common_SearchMessage));
      dates = DateFunctions.GetSelectedDates(DateFrom, DateTo);

              var list = string.Empty;
              var klirwseis = ", Κληρωσεις: ";
              if (num == -1)
                  list = ListTextView.Text;
              else
                  list = num.ToString();
              var nums = list.Split(',').Select(Int32.Parse).ToList();
              if (seperateCheckBox.Checked)
              {
                  DisplayLoadingMessage(false);
                  seperateCheckBox.Checked = false;
                  for (int k = 0; k < nums.Count; k++)
                  {
                      await SearchForAllNumbers(nums\[k\]);
                  }
                  return -1;
              }
              var totalCoutner = 0;
              for (int datesPos = 0; datesPos <= dates.Count; datesPos++)
              {
                 ... Do some calculations
                  }
                  HistoryTextView.Text = "Ημερομηνία: " + dates\[datesPos\] + ", Λίστα: " + list + ", Κληρώθηκε: " + totalCoutner + " φορές" + HistoryTextView.Text;
                  if (showListsCheckBox.Checked)
                      HistoryTextView.Text = klirwseis + HistoryTextView.Text;
              }
              DisplayLoadingMessage(false);
              HistoryTextView.Text = ".\\n" + HistoryTextView.Text;
              return totalCoutner;
              return 0;
          }
      

      And i want to be able to cancel it when its running so i have created this function

      private async Task SearchFoNumbersAsync()
      {
      ActiveCancellationTokenSource = new CancellationTokenSource();
      DrawResultsTypeEnum searchType = (DrawResultsTypeEnum)ShowResultsSpinnerPosition;

              var task = Task.Run(async () =>
              {
                  if (searchType == DrawResultsTypeEnum.AllNumbers)
                      await SearchForAllNumbers();
                  else if (searchType == DrawResultsTypeEnum.AnyWinningCombination)
                      await SearchAnyWinningCombination();
                  SaveHistory();
              }, ActiveCancellationTokenSource.Token); // Pass same token to Task.Run.
      
              try
              {
                  await task;
              }
              catch (System.OperationCanceledException e)
              {
      
      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Keep taking code out until it works, then start adding it back in. If nothing works, start over.

      It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

      E 1 Reply Last reply
      0
      • L Lost User

        Keep taking code out until it works, then start adding it back in. If nothing works, start over.

        It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

        E Offline
        E Offline
        Exoskeletor
        wrote on last edited by
        #3

        thanks, this helped, i found the reason of that but now i see that if i cancel the task, all the already running functions will keep running. im not sure if the best approach is to add some if (token.iscancellationrequested) or to make all the functions to tasks that can take a token

        L 1 Reply Last reply
        0
        • E Exoskeletor

          thanks, this helped, i found the reason of that but now i see that if i cancel the task, all the already running functions will keep running. im not sure if the best approach is to add some if (token.iscancellationrequested) or to make all the functions to tasks that can take a token

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          [How to: Cancel a Task and Its Children | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children)

          It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

          E 1 Reply Last reply
          0
          • L Lost User

            [How to: Cancel a Task and Its Children | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children)

            It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

            E Offline
            E Offline
            Exoskeletor
            wrote on last edited by
            #5

            I was reading this today but it looks to me like a worst idea of having a task that can take a cancellation token so i will try to find more approaches on how to cancel task and its childrends

            L 1 Reply Last reply
            0
            • E Exoskeletor

              I was reading this today but it looks to me like a worst idea of having a task that can take a cancellation token so i will try to find more approaches on how to cancel task and its childrends

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              If you don't "like" MS samples, you're going to be in for a lot of headaches.

              It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

              E 1 Reply Last reply
              0
              • L Lost User

                If you don't "like" MS samples, you're going to be in for a lot of headaches.

                It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

                E Offline
                E Offline
                Exoskeletor
                wrote on last edited by
                #7

                a general sample might not be the best solution for every situation. my code in the first post also is based on MS samples

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups