Note that there are some explanatory texts on larger screens.

plurals
  1. POParallel.ForEach iterating items in collection multiple times
    text
    copied!<p>I have a Parallel.ForEach running inside a Task. It iterates over a collection of email addresses and sends a MailMessage to the SMTP queue, once it's sent it updates a table in the DB with a result.</p> <p>I can see in the DB that it's sending the MailMessage to the queue multiple times, sometimes up to 6 times. Here is my simplified code, can anyone recommend a better approach?</p> <p>On button click, I create a new Task...</p> <pre><code>CampaignManager.Broadcast.BroadcastService broadcastService = new CampaignManager.Broadcast.BroadcastService(); var task = Task&lt;CampaignManager.Broadcast.Results.Broadcast&gt;.Factory.StartNew(() =&gt; { return broadcastService.BroadcastCampaign(); }, TaskCreationOptions.LongRunning); Task.WaitAny(task); if (task.Result != null) { Broadcast.Results.Broadcast broadcastResult = task.Result; MessageBox.Show(broadcastResult.BroadcastSent.GroupName + " completed. " + broadcastResult.NumberSuccessful + " sent."); } </code></pre> <p>This creates a task, which basically gets a ConcurrentBag of subscribers (custom class), iterates over the collection and sends a message...</p> <pre><code>public Results.Broadcast BroadcastCampaign() { // Get ConcurrentBag of subscribers subscribers = broadcast.GetSubscribers(); // Iterate through subscribers and send them a message Parallel.ForEach(subscribers, subscriber =&gt; { // do some work, send to SMTP queue // Add to DB log }); // return result } </code></pre> <p>I am led to believe that ConcurrentBag's are thread-safe, so I'm not sure why it would be iterating over some in the collection multiple times. Out of a thousand it would queue at least 2 messages for 10% of the collection.</p> <p>Thanks,</p> <p>Greg.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload