Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Net.SmtpClient SendAsync() method's internal implementation

I wanted to know the internal implementation of System.Net.SmtpClient's SendAsync() method's internal implementation, If it uses the ThreadPool's Thread or only uses the current synchronization context??

In this answer it is said that it uses the threadpool's thread but when I looked at System.dll's decompiled code it didn't had any Threadpool used(or maybe I didn't understand the code).

I just wanted to know this for my implementation of sending bulk emails where I was stuck between to use SendAsync method or just use the Send() method in ThreadPool.QueueUserWorkItem...

like image 995
Rushi Soni Avatar asked Mar 08 '26 20:03

Rushi Soni


1 Answers

There are two asynchronous methods for sending emails, although the "newer" method just calls the "older" one. Neither uses the ThreadPool but both are asynchronous.

  • SendAsync is the old-style method. It exists since .NET 2.0 and doesn't use the ThreadPool. Instead, it starts an asynchronous operation using the AsyncOperationManager and signals an event when it completes. Obviously, you can't use it with async/await unless you wrap it using a TaskCompletionSource.
  • SendMailAsync is the "new" method which just wraps SendAsync with a TaskCompletionSource and returns a Task that you can await on.

In both cases the execution is asynchronous as your own thread doesn't block until SendAsync completes. On the other hand, you can't have more than one Send operation running per client, either synchronous or asynchronous.

Your best option is to create a new client for each message or batch of messages you want to send and send each message using 'SendMailAsync' to take advantage of await

like image 132
Panagiotis Kanavos Avatar answered Mar 11 '26 10:03

Panagiotis Kanavos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!