Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to have a timed callback in .NET?

Tags:

c#

.net

wpf

I want to do something like this in C# (more specifically, WPF):

Thread.Invoke(MyCallback, 1000);

Which will just call MyCallback, 1 time, 1 second from now.

What is the easiest way to do this with .NET? Do I have to setup a Timer and hook an event?

like image 638
NotDan Avatar asked Dec 22 '22 12:12

NotDan


1 Answers

You can use System.Timers.Timer to do this without spawning your own thread. Implement the Elapsed callback to do what you want, setting Enabled true and AutoReset false to achieve a single invocation.

Make sure you Dispose the Timer object once you are done with it!

like image 143
Steve Townsend Avatar answered Dec 24 '22 02:12

Steve Townsend