I am coding a MVC 5 internet application, where I retrieve many Account
objects that need emails sent to, then I send the emails. After the emails have been sent, I need to update a DateTime
field in each Account
object to store a value to show that the email has been sent.
Here is my code:
public async Task SendDailyExpirationEmails(int dayInterval)
{
IEnumerable<Account> freeTrialAccounts = GetFreeTrialAccountsForSendDailyExpirationEmails(dayInterval).ToList();
IEnumerable<Account> paidServiceAccounts = GetPaidServiceAccountsForSendDailyExpirationEmails(dayInterval).ToList();
await SendFreeTrialSubscriptionExpirationEmails(freeTrialAccounts);
await SendPaidSubscriptionExpirationEmails(paidServiceAccounts);
}
The SendEmail functions, for both the freeTrialAccounts
and paidServiceAccounts
, use a ForEach Loop
to loop through each Account
in the IEnumerable
.
My question is this:
Should I update the DateTime
field after both the SendEmail functions have been completed or within the SendEmail functions?
Is there a common coding practice for this situation?
Thanks in advance.
To maintain the precision of the DateTime value so that it's as correct as possible while reducing database calls, you will want to make record of it as soon as the email has sent, but wait to persist the information until your email process has completed.
I would say have a class property keep track of when each email was sent and then once all emails have been sent, make your call(s) to the database to update the sent date/time(s).
That said if you have some other job/task/application that relies on that information as soon as possible, then you will need to persist the data as soon as the email is sent. Otherwise I don't see a problem with delaying it.