简体   繁体   中英

C# Limit Calls Per Second

I am calling a service that only allows 10 calls per second. I am using Stopwatch and Thread.Sleep to limit my calls. 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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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