2

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...

Community
  • 1
  • 1
Rushi Soni
  • 1,088
  • 1
  • 13
  • 21

1 Answers1

15

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

svick
  • 236,525
  • 50
  • 385
  • 514
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236