title: Throttling speed of email sending process
body: <p>Sorry the title is a bit crappy, I couldn't quite word it properly.</p>
  
  <p>Edit: I should note this is a console c# app</p>
  
  <p>I've prototyped out a system that works like so (this is rough pseudo-codeish):</p>
  
  <pre><code>var collection = grabfromdb();
  
  foreach (item in collection) {
      SendAnEmail();
  }
  </code></pre>
  
  <p>SendAnEmail:</p>
  
  <pre><code>SmtpClient mailClient = new SmtpClient;
  mailClient.SendCompleted += new SendCompletedEventHandler(SendComplete);
  mailClient.SendAsync('the mail message');
  </code></pre>
  
  <p>SendComplete:</p>
  
  <pre><code>if (anyErrors) {
      errorHandling()
  }
  else {
      HitDBAndMarkAsSendOK();    
  }
  </code></pre>
  
  <p>Obviously this setup is not ideal. If the initial collection has, say 10,000 records, then it's going to new up 10,000 instances of smtpclient in fairly short order as quickly as it can step through the rows - and likely asplode in the process.</p>
  
  <p>My ideal end game is to have something like 10 concurrent email going out at once.</p>
  
  <p>A hacky solution comes to mind: Add a counter, that increments when SendAnEmail() is called, and decrements when SendComplete is sent. Before SendAnEmail() is called in the initial loop, check the counter, if it's too high, then sleep for a small period of time and then check it again.</p>
  
  <p>I'm not sure that's such a great idea, and figure the SO hive mind would have a way to do this properly.</p>
  
  <p>I have very little knowledge of threading and not sure if it would be an appropriate use here. Eg sending email in a background thread, first check the number of child threads to ensure there's not too many being used. Or if there is some type of 'thread throttling' built in.</p>
  
  <hr />
  
  <h2>Update</h2>
  
  <p>Following in the advice of Steven A. Lowe, I now have:</p>
  
  <ul>
  <li>A Dictionary holding my emails and a unique key (this is the email que</li>
  <li>A FillQue Method, which populates the dictionary</li>
  <li>A ProcessQue method, which is a background thread. It checks the que, and SendAsycs any email in the que.</li>
  <li>A SendCompleted delegate which removes the email from the que. And calls FillQue again.</li>
  </ul>
  
  <p>I've a few problems with this setup. I think I've missed the boat with the background thread, should I be spawning one of these for each item in the dictionary? How can I get the thread to 'hang around' for lack of a better word, if the email que empties the thread ends.</p>
  
  <hr />
  
  <h1>final update</h1>
  
  <p>I've put a 'while(true) {}' in the background thread. If the que is empty, it waits a few seconds and tries again. If the que is repeatedly empty, i 'break' the while, and the program ends... Works fine. I'm a bit worried about the 'while(true)' business though..</p>