SmtpClient.SendAsync () does not receive all messages I sent

I just wrote some test code looking at System.Net.Mail.SmtpClient sending me the same messages.

int numClients = 10; List<SmtpClient> mailClients = new List<SmtpClient>(); for (int i = 0; i < numClients; i++) { mailClients.Add(new SmtpClient(smtpHost)); } MailMessage msg = new MailMessage(" myAddress@eg.com ", " myAddress@eg.com ", "test message", "" ); foreach (SmtpClient c in mailClients) { c.SendAsync(msg, null); } 

All this is normal and runs without any problems, except that I only receive "n - 1" messages. If I send 10 messages, I get only 9 in my inbox. If I send 50, I get only 49, etc.

Note. If I change the code to use send lock, I always get the right amount of messages. eg.

 foreach (SmtpClient c in mailClients) { c.Send(msg); } 

Any ideas?

+4
source share
1 answer

Here are some notes that might help:

  • Create only one SmtpClient.
  • Create multiple posts.
  • SmtpClient implements IDisposable. Wrap it when using.
  • MailMessage also implements IDisposable.

I suspect you might encounter an error / problem with multiple instances of SmtpClient that wrap the same SMTP server. Using one instance may solve the problem.

UPDATE

In MSDN:

After calling SendAsync, you must wait for the email transfer to complete before attempting to send another email message using Send or SendAsync.

http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx

Therefore, given your situation, there is almost no benefit in using SendAsync over Send. Your loop is probably stomping something because you are not waiting for the previous SendAsync to complete.

Here are a few thoughts:

  • SendAsync will do almost the same thing as Send if you send a bunch of emails. Just click Submit.
  • If you need parallel shipping, use the Producer / Consumer template. One (or more) creating thread dumps the material into the queue for sending, and several consumption threads use one SmtpClient to send messages. This template is surprisingly easy to implement with BlockingCollection. See Example at MSDN http://msdn.microsoft.com/en-us/library/dd267312.aspx
  • If you use enough threads, your SMTP server will become a bottleneck. Remember when you overload it.
+3
source

Source: https://habr.com/ru/post/1438761/


All Articles