title: C# - Kill task after timout
body: <p>I have this method ExecuteAllAsync() which uses the field List jobs and executes asynchronously all Jobs in the list . I want to set a timeout to kill the job and stop the execution if it takes to long or no longer necessary. I tried doing so in the following code:</p>
  
  <pre><code>
          //Execute all jobs async
          public async void ExecuteAllAsync()
          {
              if (jobs.Count()==0)
                  return;
              List&lt;Task&gt; tasks = new List&lt;Task&gt;();
              foreach (Job job in jobs.ToArray())
              {
                  int timeout = 500; 
  
                  Task t = Task.Run(() =&gt; { 
                       ExecuteJob(job) // Do Work Here
                  });
                  tasks.Add(t);
                  if (!t.Wait(timeout))
                       //Log Timeout Error
              }
              await Task.WhenAll(tasks);
          }
  </code></pre>
  
  <p>This doesn't work. I tried to also put Thread.Sleep(1000) in the ExecuteJob() Function to make all tasks timeout and and the result is that only some of the jobs timeout and some execute fully. I also use stopwatch to check how long the job takes and I see some of them takes more than 1 second.</p>
  
  <p>Currently the timeout is set 500 ms but in the future each task will have different timeout value:</p>
  
  <pre><code>int timeout = (int)(job.TimeToKill() - DateTime.Now).TotalMilliseconds
  </code></pre>
  
  <p>How do I execute all jobs in list asynchronously while setting a timeout to each task? 
  Thanks in advance.</p>