Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 只能每X秒运行一次内部代码的委托_C#_Loops_Timer - Fatal编程技术网

C# 只能每X秒运行一次内部代码的委托

C# 只能每X秒运行一次内部代码的委托,c#,loops,timer,C#,Loops,Timer,我正在尝试创建一个方法,该方法将返回一个可以每毫秒调用一次的委托,但我想限制它在每次调用时都运行缓慢的操作,比如说,至少每5秒钟运行一次 试图通过计时器和秒表实现这一点,但无法坚持采用价格合理的解决方案 第一次进近: public Func<bool> GetCancelRequestedFunc(string _taskName) { var checkStatus = false; var timer = new Timer(5000); timer.El

我正在尝试创建一个方法,该方法将返回一个可以每毫秒调用一次的委托,但我想限制它在每次调用时都运行缓慢的操作,比如说,至少每5秒钟运行一次

试图通过计时器和秒表实现这一点,但无法坚持采用价格合理的解决方案

第一次进近:

public Func<bool> GetCancelRequestedFunc(string _taskName)
{
    var checkStatus = false;
    var timer = new Timer(5000);
    timer.Elapsed += (sender, args) => { checkStatus = true; };

    return () =>
    {
        if (checkStatus)
        {
            bool result;
            checkStatus = false;

            //long operation here

            return result;
        }

        return false;
    };
}
public Func<bool> GetCancelRequestedFunc(string _taskName)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    return () =>
    {
        var mod = stopwatch.ElapsedMilliseconds % 5000;     
        if (mod > 0 && mod < 1000)
        {
            bool result;

            //long operation here

            return result;
        }

        return false;
    };
}
这个有效。。。但非常不可靠,因为若调用委托,则检查似乎在第6秒执行。但是,它将在第6秒钟内一直被调用


您能说出第1种方法有什么问题吗?或者建议使用更好的方法吗?

您在这里并不需要任何计时器,只需记住上次执行函数的时间:

public Func<bool> GetCancelRequestedFunc(string taskName)
{
    DateTime lastExecution = DateTime.Now;

    return () =>
    {
        if(lastExecution.AddMinutes(5)<DateTime.Now) 
        {
            lastExecution = DateTime.Now;
            bool result;

            //long operation here

            return result;
        }

        return false;
    };
}
public Func GetCancelRequestedFunc(字符串taskName)
{
DateTime lastExecution=DateTime.Now;
return()=>
{
if(lastExecution.AddMinutes)(5)