Waqar
Waqar

Reputation: 99

Using thread to slow down the loop

I am new with C#. I am running a loop to send emails to subscribed users. I need to slow down the loop because I only want to send 10 email/second. Is using Thread.sleep good way to slow down the loop? please see code below.

            while (rdr.Read())
            {
                System.Threading.Thread.Sleep(100);

                //send email code here
            }

Thanks

Upvotes: 0

Views: 2433

Answers (5)

Rob Levine
Rob Levine

Reputation: 41328

Why don't you have a System.Timers.Timer that fires up every second and sends up to ten messages from your message queue every second.

This way you really do have complete control over the process and are not guessing about speed/timings of your email sender.

Perhaps something like this:

public class EmailSender
{
    private System.Timers.Timer _timer = new Timer(1000);

    public EmailSender()
    {
        _timer.Elapsed += (object sender, ElapsedEventArgs args) => SendEmail();
    }

    public void StartSender()
    {
        _timer.Enabled = true;
    }

    public void SendEmail()
    {
        // you *may* want to stop your timer here in case the send of the ten overruns 1s.
        _timer.Enabled = false;

        // code here to send UP TO ten emails

        // re-enable timer, if you stopped it above.
        _timer.Enabled = true;
    }
}

In short - no - your original approach is not good.

  • How do you know how long to make it sleep for to get 10 messages sent?
  • What happens if the machine is running slowly anyway?
  • What happens if you deploy to a faster machine?
  • etc..

Upvotes: 4

jason
jason

Reputation: 241711

Is using Thread.sleep good way to slow down the loop?

Huh, what, no!

I need to slow down the loop because I only want to send 10 email/second

If that's your spec, then write code that obeys that spec! Sleep as you are using it doesn't ensure that spec. Use a Timer that fires once a second and sends at most ten emails, or write a queue that guarantees it only serves ten items per second.

Upvotes: 1

Tigran
Tigran

Reputation: 62276

Don't see any problem in the approach defined by you, at least looking on the question provided. I immagine you send 10 mails, and after wait for a while so they go out from outbox, for some reason.

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

Yes, you can do it, but what is the type of rdr? If it is SqlDataReader or some other reference to external data(file, database, network and etc.), better to fetch all data first than to keep rdr open for a long time

Upvotes: 0

BlueM
BlueM

Reputation: 6888

If that is a GUI application you should use a timer to work through a Queue. In a singlethreaded console application that may be ok. If your code is in a separate thread Thread.Sleep is ok.

I suggest you to not block the reader too long. But we don't see whats behind the reader.

Upvotes: 2

Related Questions