title: Safely stop long running task
body: <p>How can I stop a long running task (.net 4)?</p>
  <p>I have implemented TPL and tried using the <code>CancellationTokenSource</code> but it doesn’t seem to work for my scenario. All examples I’ve seen assume you’re doing work in a while-loop so that you can check if the task has been cancelled, whereas I just have a single operation that takes long. I cannot wait for the work to be completed as I need to assume it might never complete.
  Here is the code I have tried:</p>
  <pre><code>bool? result = null;
  
  var cs = new CancellationTokenSource();
  var ct = cs.Token;
  
  var doWorkTask = new Task(() =&gt;
  {
      Console.WriteLine(&quot;start dowork task&quot;);
  
      result = Work.LongRunning();
   }, ct);
  
  doWorkTask.Start();
  
  Task.WaitAny(new Task[] { doWorkTask }, timetowait);
  
  if (doWorkTask.IsCompleted)
  {
      Console.WriteLine(&quot;dowork task completed&quot;);
  
      doWorkTask.Dispose();
  }
  else
  {
      Console.WriteLine(&quot;dowork task has timedout&quot;);
  
      cs.Cancel();
  
      throw new TimeoutException(&quot;Timeout hit.&quot;);
  }
  </code></pre>
  <p>The code works but the task is never disposed if the timeout happens and the work that is being done accesses 'unmanaged code' i.e. resources. That said the <code>IsCancelledRequested</code> cannot be used in <code>Work.LongRunning()</code> so I cannot <code>ThrowIfCancellationRequested</code>.</p>
  <p>I am open to other ideas as well as I have tried <code>BackgroundWorker</code> but that also doesn’t seem to fit.</p>
  <p>New example:</p>
  <pre><code>var service = new System.ServiceProcess.ServiceController(ServiceName, ServerName);
  
  var serviceTask = Task.Factory.StartNew(() =&gt;
  {
      result = (service.Status == ServiceControllerStatus.Running
           || service.Status == ServiceControllerStatus.StartPending);
  }, cs.Token);
  
  serviceTask.Wait(2000, cs.Token);
  
  if (!serviceTask.IsCompleted)
  {
      cs.Cancel();
  }
  </code></pre>