c# - Calling Method only once from a Threading.Timer -


i have system.threading.timer fires (let's every second simplicity), in callback need call action (which passed in via constructor, sits in class) within processing (let's takes 2+ seconds), how prevent processing logic being called multiple times? seems lock() doesn't work within action call? i using .net 3.5.

public testoperation(action callbackmethod) {     this.timer = new system.threading.timer(timer_elapsed, callbackmethod, timerinterval, timeout.infinite); }  private void timer_elapsed(object state) {     action callback = (action) state;     if (callback != null)     {         callback();     } }  // example of callback, in class.  private void callbackmethod() {     // how can stop running every 1 second? lock() doesn't seem work here     thread.sleep(2000); } 

thanks!

there's nothing pretty having solve problem. note using lock bad idea, make threadpool explode when callback consistently takes time. happens when machine gets loaded. using monitor.tryenter() safe alternative. not pretty either, you'll arbitrarily lose callbacks.

it gets heckofalot easier if set period argument 0. timer can tick once. automatically have hard guarantee callback cannot re-entered. have call change() @ end of method restart timer. use fixed value or calculate new duetime value based on actual amount of time expired, either reasonable choices.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -