简体   繁体   English

每秒C#限制呼叫

[英]C# Limit Calls Per Second

I am calling a service that only allows 10 calls per second. 我正在呼叫仅允许10次呼叫的服务。 I am using Stopwatch and Thread.Sleep to limit my calls. 我正在使用Stopwatch和Thread.Sleep限制通话。 Are these the correct tools for this job, or should I be using Timers or some other tool. 这些是该工作的正确工具,还是我应该使用计时器或其他工具?

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

Thank you in advance for any help! 预先感谢您的任何帮助!

As you already know it can be 10 calls / sec. 如您所知,它可以是10个呼叫/秒。 Code can be simple as follows : 代码可以很简单,如下所示:

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

Edit : Ok got it, please see if following alternative will be helpful, it only allows 10 or less calls per second depending on how its performing : 编辑:好的,请查看以下替代方法是否会有所帮助,它每秒仅允许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
                }
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM