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:
        //Execute all jobs async
        public async void ExecuteAllAsync()
        {
            if (jobs.Count()==0)
                return;
            List<Task> tasks = new List<Task>();
            foreach (Job job in jobs.ToArray())
            {
                int timeout = 500; 
                Task t = Task.Run(() => { 
                     ExecuteJob(job) // Do Work Here
                });
                tasks.Add(t);
                if (!t.Wait(timeout))
                     //Log Timeout Error
            }
            await Task.WhenAll(tasks);
        }
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.
Currently the timeout is set 500 ms but in the future each task will have different timeout value:
int timeout = (int)(job.TimeToKill() - DateTime.Now).TotalMilliseconds
How do I execute all jobs in list asynchronously while setting a timeout to each task? Thanks in advance.
 
     
    