Does C# have a built in way to throttle a function's number of calls?

If you use Reactive Extensions, you can take advantage of the Observable.Throttle() method: https://msdn.microsoft.com/en-us/library/hh229400(v=vs.103).aspx

The Reactive Extensions page can be found at http://reactivex.io/


There is no built-in way. You'll need to find a library or implement this yourself.


As other answers have said, you would have to implement this yourself. Fortunately, it's fairly easy. Personally, I would create a Queue<ObjectWithYourFunction'sArguments>. You might then have a ThrottledFunction that queues stuff up and, if needed, starts a background task to wait the appropriate length of time.

Totally untested example code:

class ThrottleMyFunction
{
    private class Arguments
    {
        public int coolInt;
        public double whatever;
        public string stringyThing;
    }

    private ConcurrentQueue<Arguments> _argQueue = new ConcurrentQueue<Arguments>();
    private Task _loop;

    //If you want to do "X times per minute", replace this argument with an int and use TimeSpan.FromMinutes(1/waitBetweenCalls)
    public void ThrottleMyFunction(TimeSpan waitBetweenCalls)
    {
        _loop = Task.Factory.StartNew(() =>
        {
            Arguments args;
            while (true)
            {
                if (_argQueue.TryDequeue(out args))
                    FunctionIWantToThrottle(args.coolInt, args.whatever, args.stringyThing);
            }

            Thread.Sleep(waitBetweenCalls);

        });
    }

    public void ThrottledFunction(int coolerInt, double whatevs, string stringy)
    {
        _argQueue.Enqueue(new Arguments() { coolInt = coolerInt, whatever = whatevs, stringyThing = stringy });
    }
}

Tags:

C#