title: CancellationToken for a Task that acquires a lock
body: <p>Using a CancellationTokenSource on a task thats acquires a lock</p>
  
  <p>If the thread acquires the lock when the cancelation occures, it does not release the lock</p>
  
  <p>BTW, the thread needs to stop immediately, without finnishing the work</p>
  
  <p>This is an example for such a code:</p>
  
  <pre><code>var cancellationTokenSource = new CancellationTokenSource;
  
  Task.Run(new Action (() =&gt; 
  { 
      while(true)
      {
          lock (locker)
          {
              DoSomething();    
          }
  
          DoAnotherThing();
  
          Task.Delay(1000, cancellationTokenSource.Token);    
      }
  }), cancellationTokenSource.Token);
  </code></pre>
  
  <p>I've found several ways to handle it, but I've wanted to hear some suggestions</p>
  
  <p>Thanks</p>
  
  <p>EDIT: To answer @spender question, this is the implementation a thought of (shortened) :</p>
  
  <pre><code>    object locker = new object();
      var cancellationTokenSource = new System.Threading.CancellationTokenSource;
      var token = cancellationTokenSource.Token;
  
      Task.Run(new Action (() =&gt; 
      { 
  
  
          while(true)
          {
              lock (locker)
              {
                  using (token.Register(() =&gt; token.ThrowIfCancellationRequested()))
                  {
                      break;
                  };
  
                  DoSomething();    
              }
  
              DoAnotherThing();
  
              Task.Delay(1000, cancellationTokenSource.Token);    
          }
      }), cancellationTokenSource.Token);
  </code></pre>