使用线程来减慢循环

时间:2012-02-23 16:26:45

标签: c# asp.net multithreading loops

我是C#的新手。我正在运行循环以向订阅用户发送电子邮件。我需要放慢循环速度,因为我只想发送10封电子邮件/秒。使用Thread.sleep是减慢循环的好方法吗?请参阅下面的代码。

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

                //send email code here
            }

由于

5 个答案:

答案 0 :(得分:4)

为什么你没有每秒发出一次System.Timers.Timer并且每秒从你的消息队列中发送最多十条消息。

通过这种方式,您确实可以完全控制流程,而不是猜测电子邮件发件人的速度/时间。

也许是这样的:

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;
    }
}

简而言之 - 不 - 你原来的做法并不好。

  • 你怎么知道让它睡了多长时间才能收到10封邮件?
  • 如果机器运行缓慢会怎样?
  • 如果部署到更快的计算机会发生什么?
  • 等。

答案 1 :(得分:2)

如果这是一个GUI应用程序,您应该使用计时器来处理Queue。在单线程控制台应用程序中可能没问题。如果你的代码在一个单独的线程中Thread.Sleep就可以了。

我建议你不要长时间阻止读者。但是我们看不到读者背后的什么。

答案 2 :(得分:1)

  

使用Thread.sleep减慢循环的好方法吗?

嗯,什么,不!

  

我需要放慢循环速度,因为我只想发送10封电子邮件/秒

如果这是您的规范,那么编写符合该规范的代码!在您使用它时睡觉并不能确保规格。使用每秒触发一次的Timer并发送最多十封电子邮件,或者写一个队列,确保它每秒只能投放十个项目。

答案 3 :(得分:0)

是的,你可以做到,但是rdr的类型是什么?如果是SqlDataReader或其他对外部数据(文件,数据库,网络等)的引用,最好先获取所有数据,而不是长时间保持rdr打开

答案 4 :(得分:0)

在您定义的方法中没有看到任何问题,至少在查看提供的问题时。 我想你发了10封邮件,经过一段时间等等,所以出于某种原因,他们会从发件箱出去。