C# 如何停止函数被频繁调用

C# 如何停止函数被频繁调用,c#,C#,有一个使用硬件密钥检查许可证的功能。但是这个函数调用太频繁,执行起来需要时间。所以为了避免太多的电话,我想在一段时间后检查一下许可证 bool CheckLicense() { if(license checked in last 10 secconds) { return last status; } else { hardware access for license check return curr

有一个使用硬件密钥检查许可证的功能。但是这个函数调用太频繁,执行起来需要时间。所以为了避免太多的电话,我想在一段时间后检查一下许可证

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

编辑:可能会删除硬件密钥,因此检查一次不是好做法。还需要调用许可证检查来启用和禁用不同的按钮状态。

一般来说,我认为您需要这样的功能

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   
    }
}
private DateTime lastCheckTime=DateTime.Now.AddDays(-1);
bool CheckLicense()
{
if(lastCheckTime.AddSeconds(10)
如果您只想每10秒调用一次,可以使用以下命令:

bool CheckLicense()
{
    bool currentStatus = false;

    //hardware access for license check

    new Thread(() =>
    {
        Thread.Sleep(10000);
        CheckLicense();
        }).Start();

    return currentStatus;
}

你在代码中调用它一次,然后每10秒它就会调用自己。

每10秒检查一次许可证肯定会增加对同一功能的多次调用。您可以按照注释中的建议在程序启动时执行一次,如果确实需要检查许可证或在每次之后调用函数,您可以实际增加计时,以便知道您已检查许可证,并且调用将减少

例如,当程序启动后约10秒,您第一次检查许可证,然后将计时增加
10*2
,这将比下一次增加20,将其增加
20*2
,这将减少调用,并且您将每隔几次检查一次

bool CheckLicense()
{
    timelimit = 300;
    if(seconds > timetocheck)
    {
        return last status;
        timetocheck *= 2;
        if(timetocheck >= timelimit)
        { 
           timetocheck = 10;
        }
    }
    else 
    {
        hardware access for license check
        return current status
    }
}

该程序只是一个原型,并不意味着直接运行,也不涉及数据类型和语法。这只是为了理解能力。

如果您正在同步检查。代码,您可能希望运行新线程。如果许可证有问题,单独的线程将通过事件通知主线程:

class LicenseChecker
{
    private Timer mTimer;
    public delegate void LicenseNotValidDelegate();
    public event LicenseNotValidDelegate LicenseNotValid;

    public LicenseChecker()
    {
        mTimer = new Timer();
        mTimer.Ticket += mTimer_Tick;
        mTimer.Interval = TimeSpan.FromSeconds(10);
    }

    public void Start()
    {
        mTimer.Start();
    }

    void mTimer_Tick(object sender, EventArgs e)
    {
        if(!CheckLicense())
            LicenseNotValid?.Invoke();
    }

    private bool CheckLicense()
    { ... }
}

...
public void Main()
{
    var lLC = new LicenseChecker();
    lLC.LicenseNotValid += lLC_LicenseNotValid;
    lLC.Start();
}

void lLC_LicenseNotValid()
{
    //code when license is not valid
}

是每10秒(最多)检查一次许可证,还是检查一次并缓存结果就足够了?在程序中检查一次状态还不够吗?然后你可以在开始时设置状态。为什么不使用定时器呢?这是一个非常简单的解决方案。谢谢。@RohanSD如果对你有帮助,请将他的答案标记为正确!不,我不想每10秒钟调用一次函数。许可证检查应该只在需要时进行。好的,那么@Hakam给了您正确的答案;)这个主意不错。但是我必须调用这个函数来启用禁用按钮,所以如果我在很短的时间内持续增加时间,它将达到天和年。你可以相应地标记5分钟或10分钟的限制。请参阅editThis,它将在每10秒后继续调用license check。但我只想在需要时检查许可证。所以这对我没有帮助。重要的问题是:“你如何认识到需要检查许可证?