C#限制每秒呼叫数

时间:2015-07-10 17:45:00

标签: c#

我正在拨打一项服务,每秒只允许10次通话。我正在使用秒表和Thread.Sleep来限制我的通话。这些是这项工作的正确工具,还是我应该使用计时器或其他工具。

     public void SomeFunction() {
        Stopwatch stopwatch = new Stopwatch();
        int numCallsThisSecond = 0;

        foreach(MyEvent changedEvent in changedEvents) {
            stopwatch.Start();

            service.ChangeEvent(changedEvent);

            numCallsThisSecond += 1;
            stopwatch.Stop();
            if(numCallsThisSecond==10 && stopwatch.ElapsedMilliseconds<=1000)
                Thread.Sleep((int)(1100-stopwatch.ElapsedMilliseconds));
            if(stopwatch.ElapsedMilliseconds>1000) {
                stopwatch.Reset();
                numCallsThisSecond = 0;
            }
        }
    }

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

正如您所知,它可以是10次/秒。代码可以简单如下:

    public void SomeFunction() 
    {
        foreach(MyEvent changedEvent in changedEvents) 
        {
            service.ChangeEvent(changedEvent);
            Thread.Sleep(100);//you already know it can be only 10 calls / sec
        }
    }

编辑: 好了,请看看以下替代方案是否有用,它每秒只允许10次或更少的呼叫,具体取决于其执行方式:

    public void SomeFunction() 
    {
        DateTime lastRunTime = DateTime.MinValue;

        foreach(MyEvent changedEvent in changedEvents) 
        {
            lastRunTime = DateTime.Now;
            for (int index = 0; index < 10; index++)
            {
                if (lastRunTime.Second == DateTime.Now.Second)
                {
                    service.ChangeEvent(changedEvent);
                }
                else
                {
                    break;//it took longer than 1 sec for 10 calls, so break for next second
                }
            }
        }
    }