I am using .net compact framework 3.5
in visual studio 2008.
I have created a timer tick event to perform a job.I want to call the timer only once and after that i need to disable the timer.Please see my below code
int counter = 0;
var timer = new Timer { Enabled = true, Interval = 10000 };
timer.Tick += delegate
{
Cleanup();
};
counter++;
if (counter >= 1)
{
timer.Enabled = false;
}
I tried with timer.Enabled = false;
without any condition,what happens is the Cleanup()
function is not calling which is inside the tick event.So from google i got one more solution to use a counter.With counter also i am facing the same problem, Cleanup()
is not calling.
If i am not disable the timer,then the function is calling in every 10secs time.I need to call the Cleanup()
function only once,which is inside the timer.tick.Need help to solve this.
Thanks
Why do you need a counter:
This should be enough
timer.Tick += delegate
{
timer.Enabled = false;
Cleanup();
};
Another approach if you are using System.Timers.Timer
- use Timer.AutoReset to make it fire only once:
var timer = new System.Timers.Timer(10000) { AutoReset = false };
timer.Elapsed += (s,e)=>Cleanup();
timer.Enabled = true;
Short notation using lambda:
var timer = new Timer { Enabled = true, Interval = 10000 };
timer.Tick +=()=>{ timer.Enabled=false; Cleanup();};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.