2014-02-12 130 views
0

我想要创建一个方法,它将返回一个可以每毫秒调用一次的委托,但是我想限制它在每次调用时都运行缓慢的操作, 5秒内至少说一次。只能每X秒运行一次内部代码的代理

试图用Timer和Stopwatch实现,但不能坚持经济实惠的解决方案。

1的方法:

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; 
    }; 
} 

1的方法似乎更对我然而它不工作 - 长运在这里永远不会调用,我无法找出原因。可能是需要通过checkStatusref,但不知道如何使它在这种情况下

第二个办法:

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; 
    }; 
} 
+0

这完美的作品,谢谢。 – Vladimirs