how to time limit C# foreach loop, every iteration should run normally and go to next iteration when the previous one take longer than 30sec.
used stopwatch, timer...but those are allowing to run iteration every 30 sec, can anyone help...
Or here you've got an example with Tasks.
foreach(var item in collection)
{
int timeout = 30000;
var task = Task.Run(()=>SomeOperationAsync());
await Task.WhenAny(task, Task.Delay(timeout));
}
Naturally you could also enhance this one with a check if your operation finished before the 30 seconds and so something with a possible result.