When you start a Timer object via Start() function, it creates a new thread and waits until the elapsed time, then when the time is elapsed then The subscribed function or lambda or delegate is called from the timer created thread. So, in case of your example the timer_elapse runs on a completely different thread. See the example below from a sample WPF MainClass:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
System.Threading.Thread.CurrentThread.Name = "UI THREAD";
System.Timers.Timer t = new System.Timers.Timer(500);
System.Threading.Thread td = new System.Threading.Thread(
(obj) =>
{
Console.WriteLine("Thread");
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
while (true)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("From Lambda: Current Thread Name: " + System.Threading.Thread.CurrentThread.Name);
}
}
);
td.Name = "K's Thread";
td.Start(null);
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("t_Elapsed: Current Thread Name: " + System.Threading.Thread.CurrentThread.Name);
}
}
And Notice The output in the debug console that the Timer function's Thread name is not the same name as the UI Thread.
So you won't have to worry about hanging up your UI thread. But if you try to change some controls, it may throw exception (not always). So to perform any UI related work, it is best practice to do it in the UI thread. You can do it Getting the Dispatcher to the UI thread from Application.Current.Dispatcher
Example is below:
public partial class MainWindow : Window
{
delegate void TestDelegate();
public MainWindow()
{
InitializeComponent();
System.Threading.Thread.CurrentThread.Name = "UI THREAD";
System.Timers.Timer t = new System.Timers.Timer(500);
System.Threading.Thread td = new System.Threading.Thread(
(obj) =>
{
Console.WriteLine("Thread");
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
while (true)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("From Lambda: Current Thread Name: " + System.Threading.Thread.CurrentThread.Name);
}
}
);
td.Name = "K's Thread";
td.Start(null);
}
void DoInUIThread()
{
Console.WriteLine("DoInUIThread: Current Thread Name: " + System.Threading.Thread.CurrentThread.Name);
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("t_Elapsed: Current Thread Name: " + System.Threading.Thread.CurrentThread.Name);
TestDelegate td = new TestDelegate(DoInUIThread);
Application.Current.Dispatcher.BeginInvoke(td );
}
}