Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an object into a timer event?

Tags:

c#

timer

Ok so I am using System.Timers.Timer in .Net 4 with C#.

I have my timer object like so:

var timer = new Timer {Interval = 123}; 

I have my Timer Elapsed event handler pointed at a method like so:

timer.Elapsed += MyElapsedMethod; 

And my method looks like this:

static void MyElapsedMethod(object sender, ElapsedEventArgs e) {     Console.WriteLine("Foo Bar"); } 

I want to pass a string into this method, how do I do this?

Thanks

like image 498
JMK Avatar asked Apr 02 '12 13:04

JMK


People also ask

How do I stop a timer elapsed event?

It would have already queued before you have called Stop method. It will fire at the elapsed time. To avoid this happening set Timer. AutoReset to false and start the timer back in the elapsed handler if you need one.


2 Answers

The easiest way to do this is to change the event handler into an anonymous function. It allows you to pass the string at the point of declaration.

string theString = ...; timer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, theString);  static void MyElapsedMethod(object sender, ElapsedEventArgs e, string theString) {   ... } 
like image 78
JaredPar Avatar answered Sep 22 '22 12:09

JaredPar


If you want to be able to unregister your "Elapsed" event handler again, you shouldn't use a delegate without remembering it in a variable.

So another solution could be to create a custom class based on Timer. Just add whatever members you like and get your custom Timer object back from the "sender" argument of the "Elapsed" event handler:

class CustomTimer : System.Timers.Timer {     public string Data; }  private void StartTimer() {     var timer = new CustomTimer     {         Interval = 3000,         Data = "Foo Bar"     };      timer.Elapsed += timer_Elapsed;     timer.Start(); }  void timer_Elapsed(object sender, ElapsedEventArgs e) {     string data = ((CustomTimer)sender).Data; } 

This strategy of course works for other events and classes too, as long as the base class is not sealed.

like image 21
Michael Geier Avatar answered Sep 20 '22 12:09

Michael Geier