Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I tie an anonymous function to a Timer's tick event?

Tags:

c#

timer

If a Tick-handling function will only be used in one context (i.e. always in the same function in combination with the same Timer object), why bother make it a separate function? That's the thought that went through my head when I thought of this.

Is it possible to tie an anonymous function to a Timer's tick event? Here's what I'm trying to do.

Timer myTimer = new Timer();
myTimer.Tick += new EventHandler(function(object sender, EventArgs e) {
  MessageBox.Show("Hello world!");
});
like image 331
Pieter Avatar asked Nov 04 '10 19:11

Pieter


People also ask

What is a tick timer?

It is a device to record an object's movement by taking a spot on a paper tape at regular time intervals. A typical ticker timer is plugged into a household outlet.

Which of the following control have tick event?

When the interval elapses in timer control, the Elapsed event has occurred. A tick event is used to repeat the task according to the time set in the Interval property. It is the default event of a timer control that repeats the task between the Start() and Stop() methods.


2 Answers

You're looking for Anonymous Methods:

myTimer.Tick += delegate (object sender, EventArgs e) {
    MessageBox.Show("Hello world!");
};

You can also omit the parameters:

myTimer.Tick += delegate {
    MessageBox.Show("Hello world!");
};

In C# 3.0, you can also use a Lambda Expression:

myTimer.Tick += (sender, e) => {
    MessageBox.Show("Hello world!");
};
like image 66
SLaks Avatar answered Nov 06 '22 05:11

SLaks


A complete example would be:

    Timer timer = new Timer();
    timer.Interval = 500;
    timer.Tick += (t, args) =>
        {
            timer.Enabled = false;
            /* some code */
        };
    timer.Enabled = true;
like image 38
HuseyinUslu Avatar answered Nov 06 '22 05:11

HuseyinUslu