Rohan S D Rohan S D - 11 days ago 9
C# Question

How to stop function being called too often

There is a function which checks license with hardware key. But this function is getting called too often and takes time to execute. So to avoid too many call I want to check license after sometime.

bool CheckLicense()
{
if(license checked in last 10 secconds)
{
return last status;
}
else
{
hardware access for license check
return current status
}
}


Edit: Hardware key might be removed so checking once is not good practice. Also license check is to be called for enabling and disabling different button status.

Answer

In general I think you would need something like this.

private DateTime lastCheckTime = DateTime.Now.AddDays(-1);

bool CheckLicense()
{
    if (lastCheckTime.AddSeconds(10) < DateTime.Now)
    {
        return last status;
    }
    else 
    {
        lastCheckTime = DateTime.Now;

        // hardware access for license check
        return current status   
    }
}
Comments