2

I have a problem with sendEmailAsync and Parallel.ForEach

If I don´t use Parallel.ForEach it works perfectly, but when I try to use it this way, my console application stops and I don´t receive any response. My question: is SendEmailAsync available for parallel method?

//here is my code
Parallel.ForEach(registros, async item => 
{
   //...
   var response = await client.SendEmailAsync(myMessage).ConfigureAwait(false);   
}
0

2 Answers 2

2

The SmtpClient instance can only handle one send at a time. To do what you want you’ll need a separate instance in each thread.

But don’t overwhelm your SMTP server or it may figure you for a spammer and put you on a blocklist.

Sign up to request clarification or add additional context in comments.

1 Comment

I got it, thank you so much
1

I will first note that Parallel.ForEach should NOT be used with async methods unless you understand the inner-workings of how it works AT ALL. Generally Parallel.Foreach is prescribed for the execution of slow processes only, and your implementation will actually be slower due to the relative simple complexity of what you're trying to do.

Now, to answer your question:

is SendEmailAsync available for parallel method?

I'd reference @O.Jones' answer as the SmtpClient can only handle one send at a time.

For I/O-bound tasks like sending email, you do not want to use Parallel. This goes double if you're running on ASP.NET. Also, you don't want to use new Thread unless you're doing COM interop.

Now, if you want to do it concurrently, then you'll want to use Task.WhenAll. It also has the benefit of observing all failures but that can be better explained through other threads.

2 Comments

"...unless you understand the inner-workings of how it works." -- This exclusion is redundant. The Parallel.ForEach should never be used with async delegate period.
@TheodorZoulias, edited response with applicable reference. thanks for the catch.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.