Method can only be called again if 3 seconds is passed

I want to implement some way to prevent a method from being called several times instantly. for example imagine if I have a class like:

class Example
{
    public void MyFunction()
    {
        // do something
    }
}

User can call MyFunction but only if 3 seconds is passed since the last time it's called. If it's called before 3 seconds, nothing should happen (Call should be ignored).

How would I do that?

Edit:

I don't want to use Thread.Sleep. I was thinking of maybe using Timer class from System.Timer. But don't know how I would use it for my need.

Jon Skeet
people
quotationmark

I don't see any need to use a timer here. You can use a Stopwatch:

class Example
{
    private static readonly TimeSpan MinInterval = TimeSpan.FromSeconds(3);
    private readonly Stopwatch stopwatch = new Stopwatch(); // Stopped initially

    public void MyFunction()
    {
        if (stopwatch.IsRunning && stopwatch.Elapsed < MinInterval)
        {
            return;
        }
        try
        {
            // Do stuff here.
        }
        finally
        {
            stopwatch.Restart();
        }
    }
}

Note that this isn't thread-safe... multiple threads could execute the method at the same time, on the same instance. Each instance uses a separate stopwatch though, so there could be multiple instances being used by multiple threads - if you want to prohibit calls across all instances, you'd want to use a static field for the stopwatch, and definitely add locking in order to access it safely.

Also note that although you could use a DateTime to detect the last execution time, that can easily go wrong via the user changing the system clock.

The use of try/finally here is to avoid multiple calls in quick succession which fail due to exceptions being thrown. Again, that may not be what you want... you should consider whether you do want the stopwatch to be reset when a call fails.

people

See more on this question at Stackoverflow