title: Cancel task in another class C#
body: <p>I have a problem with the cancellationTokenSource in C#</p>
  <pre><code>public class Building {
      public CancellationTokenSource BuildTokenSource;
  
      public void StartBuilt()
      {
          BuildTokenSource = new CancellationTokenSource();
  
          buildingService.buildTask = Task.Run(async () =&gt;
          {
              await clock.Delay(BUILT_TIME);
          }, BuildTokenSource.Token);
      }
  
      public void CancelBuilt()
      {
          if (BuildTokenSource != null)
          {
              BuildTokenSource.Cancel();
          }
      }
  }
  </code></pre>
  <p>In another class in want to detect if the task is cancel like this but it doesn't work. The catch exception in never triggered</p>
  <pre><code>public async Task&lt;Building&gt; GetBuildingOfUserTask()
      {
          double remainingTime = unitService.GetRemainingTime();
  
          if (remainingTime &lt;= 2000 &amp;&amp; remainingTime &gt; 0.0)
          {
              Building building = GetBuilding();
              CancellationToken cancellation = building.BuildTokenSource.Token;
              try
              {
                  await buildTask;
              }
              catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
              {
                  return GetBuildingOfUser();
              }
          }
          return GetBuildingOfUser();
      }
  </code></pre>
  <p>Anyone have any idea why this is not working and in this case a solution?</p>