1
\$\begingroup\$

I am trying to basically do the following

  1. Get record from db.
  2. Loop through records and send mail out for each record.
  3. Update database records.

I would like to know what is the most optimal way to do this, including introducing some async if that would be best.

So I put a build-able sample together that goes from A-Z and I am looking for feedback on the best way to make this most efficient, basically in the need I would like to update the record in the db and end mail for that record

Main

class Program
{
    static void Main(string[] args)
    {
        var app = new App(new Sender(), new DbContext()); //params are DI'ed
        app.Run();
    }
}

App Class

public class App
{
    private readonly ISender _sender;
    private readonly DbContext _context;
    public App(ISender sender, DbContext context)
    {
        _sender = sender;
        _context = context;
    }

    public void Run()
    {
        var listFromDB = _context.Alerts;
        foreach (var alert in listFromDB)
        {
            _sender.Send(alert);
            alert.IsComplete = true;
        }
        _context.SaveChanges();
    }
}

Sender

public interface ISender
{
    void Send(Alert alert);
}
public class Sender:ISender
{

    public void Send(Alert alert)
    {
        var smtpClient = new SmtpClient();
        //....
        var msg = new MailMessage();
        smtpClient.SendMailAsync(msg);
    }
}

Support

public class Alert
{
    public string Title { get; set; }
    public string EmailAddress { get; }
    public bool IsComplete { get; set; }
}
public class DbContext //Entity Framework Core 2.0 object
{
    public List<Alert> Alerts { get; set; }

    public void SaveChanges()
    {
        //save to db;
    }
}
\$\endgroup\$
  • \$\begingroup\$ How many alerts would typically be sent? \$\endgroup\$ – Gert Arnold Nov 19 '17 at 20:55
  • \$\begingroup\$ @GertArnold in my case the process runs every 5 min so very little(10-20), however I would like to have this code to be salable so it can handle couple thousand each run. Which really makes the SaveChanges not ideal as that is extremely slow at bulk updates \$\endgroup\$ – Zoinky Nov 19 '17 at 20:57
  • \$\begingroup\$ Does that matter though? This looks like something that could run unattended. Also with that kind of numbers you should start worrying about how many emails a mail provider would allow you to send in a batch. \$\endgroup\$ – Gert Arnold Nov 20 '17 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.