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
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.
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) { ... }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With