Search code examples
c#.netplinq

Parallel ForEach wait 500 ms before spawning


I have this situation:

var tasks = new List<ITask> ...
Parallel.ForEach(tasks, currentTask => currentTask.Execute() );

Is it possible to instruct PLinq to wait for 500ms before the next thread is spawned?

System.Threading.Thread.Sleep(5000);

Solution

  • You are using Parallel.Foreach totally wrong, You should make a special Enumerator that rate limits itself to getting data once every 500 ms.

    I made some assumptions on how your DTO works due to you not providing any details.

    private IEnumerator<SomeResource> GetRateLimitedResource()
    {
        SomeResource someResource = null;
        do
        {
            someResource = _remoteProvider.GetData();
    
            if(someResource != null)
            {
                 yield return someResource;
                 Thread.Sleep(500);
            }
        } while (someResource != null);
    }
    

    here is how your paralell should look then

    Parallel.ForEach(GetRateLimitedResource(), SomeFunctionToProcessSomeResource);