0

I am trying to limit the number of concurrent tasks that can run in parallel for each call of Create to 5 tasks.
In my code Parallel.ForEach does not seem to do any throttling at all.
How do I limit the number of concurrent tasks Create creates?

public async Task Create(List<FormModel> forms)
 {
     var tasks = new List<Task>();

     Parallel.ForEach(forms, new ParallelOptions { MaxDegreeOfParallelism = 5 }, form =>
     {
         tasks.Add(makePdfAsync(form));
     });
     await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(TimeSpan.FromMinutes(10)));
 }

 public async Task makePdfAsync()
 {
     var message = new PdfMessageModel();
     message.forms = new List<FormModel>() { form };

     var retry = 10;
     var uri = new Uri("http://localhost.:8007");
     var json = JsonConvert.SerializeObject(message);

     using (var wc = new WebClient())
     {
         wc.Encoding = System.Text.Encoding.UTF8;

         // reconnect with delay in case process is not ready
         while (true)
         {
             try
             {
                 await wc.UploadStringTaskAsync(uri, json);
                 break;
             }
             catch
             {
                 if (retry-- == 0) throw;
             }
         }
     }
 }

EDIT: The suggestion of semaphoreSlim did not work any better. The solution was to move the code that limit the concurrent tasks into the try clause of makePdfAsync() as tasks.Add(makePdfAsync(form)) will never be limited regardless of what thread limiting construct you use.

I had foolishly assumed the await from makePdfAsync() would make all of makePdfAsync() awaited higher up too..

Jeppe
  • 1,424
  • 2
  • 15
  • 36
  • You might try looking at http://stackoverflow.com/questions/10806951/how-to-limit-the-amount-of-concurrent-async-i-o-operations to see of that answers your question. – David A May 12 '17 at 11:21
  • `Parallel` is for synchronous code only. The correct tool to limit asynchronous concurrency is `SemaphoreSlim`. See recipe 11.5 in my book. – Stephen Cleary May 12 '17 at 12:51

0 Answers0