Here is the code before refactoring:
public void PerformMultiTask(IEnumerable<string> ids) { foreach(string id in ids) { Task.Run(()=>PerformSingleTask(id)); } }
The reason for the time limit is because the scheduler which triggers the method will run in intervals. So, we need to make sure that method execution finishes before the scheduler starts again. We also want the ability to control the concurrency of the execution.
Here is the code after refactoring:
public void PerformMultiTask( int timeLimitInSeconds, int maxConcurrency, IEnumerable<string> ids) { DateTime timeLimit = DateTime.UtcNow.Add(new TimeSpan(0,0,0,timeLimitInSeconds)); Parallel.ForEach( ids, new ParallelOptions() { MaxDegreeOfParallelism = maxConcurrency }, (id, loopState) => { if (DateTime.UtcNow < timeLimit) PerformSingleTask(id); else loopState.Stop(); }); }
I use Parallel.ForEach method which accepts three parameters:
- the list IEnumerable<T>
- ParallelOptions instance
- Action(T,ParallelLoopState)
Feel free to comment or to suggest improvement of the code.
No comments:
Post a Comment