I'm creating Windows Service that sends batches of emails every 5 minutes.
I want to send batches of 10-100 emails every 5 minutes. This is extreme edge case. Batches are sent every 5 minutes and normally consist of up to 10 emails.
I'm using SmtpClient from System.Net.Mail namespace.
What is proper lifetime of SmtpClient object? Should I create one every time batch is send? Or should I create one on Service start and never dispose of it?
As of .NET 4.0 the SmtpClient pools connections so you might keep on it for a while. It's probably best to dispose it after you finished sending a batch.
From MSDN: https://msdn.microsoft.com/en/us/library/system.net.mail.smtpclient(v=VS.100).aspx
You should always utilise
using
You should always dispose of anything that implements IDisposable as soon as you are finished with it.The SmtpClient class in .NET 4.0 implements IDisposable so be sure to use it!
To quote MSDN:
If you find yourself doing async related tasks then you can make a new instance for each email to prevent blocking yourself.You can use the following.
At Request - Best option for Bulk Send Emails
As noted above you can reuse the same client. If you keep it all on the same thread I recommend you just use one client
MSDN States:
However it goes on to say:
So assuming you dispose of your Client when complete it is fine.
There is discussion of a number of SMTP related topics linked below as I recently found myself asking the same question
More from Stackoverflow:
What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0
How to dispose objects having asynchronous methods called?
Related Reading:
MSDN SmtpClient
Implementing Finalize and Dispose to clean up managed resources
First of all it is a very good practice to use any object whenever needed untill and unless you needs its utility throughout the app.
Secondly you should create SmtpClient's object every time you need it and to properly dispose it, for that use the using tags as described above by Glitch100.