Question

I'm writing a code that sends 2 codes to 2 different emails (to check that owner of both emails are the same person). And I got the error:

System.InvalidOperationException: An asynchronous call is already in progress. It must be completed or canceled before you can call this method.

Well I can simply avoid this error sending the second email after the sending of the first one completes, but the question is that if so many users at the same time request email sending (forgotten password, email change, registration, ...) would it cause problem? or I will get this error only when they are executed repeatedly at the same page?

Thanks in advance,
Ashkan

Was it helpful?

Solution

The purpose of the SendAsync method is not to block the calling thread; however, you must wait for the SendAsync method to finish before you can send a new email on the same SmtpClient instance. In other words, create 2 instances, one for each email, and send them both asynchronously if you want.

From MSDN:

After calling SendAsync, you must wait for the e-mail transmission to complete before attempting to send another e-mail message using Send or SendAsync.

OTHER TIPS

As Icarus pointed out, you have to wait for the SendAsync to finish before calling it on the same instance. In addition to that, it is possible to have ThreadPool starvation, but your mileage will vary based on your implementation. Internally, SendMailAsync uses a ThreadPool thread to perform the task. I wouldn't be concerned if it's just an email here and there though.

No Separate instances won't be a problem. if many users send requests at the same time they each will be different instances.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top