Using Visual Studio 2015, visual C# windows application.
I need a timer that empties a queue in the main thread because some UI components are modified. I coded this:
public Form1()
{
InitializeComponent();
Q = new ConcurrentQueue<amsg>();
timer = new System.Timers.Timer(100);
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
clsUdpMsg msg;
while (Q.TryDequeue(out msg)) handleRx(msg);
}
but the Elapsed event executes in a worker thread...?
If I put a timer on the main form at design time the generated prototype is slightly different:
private void timer1_Tick(object sender, EventArgs e)
{
amsg msg;
while (Q.TryDequeue(out msg)) handleRx(msg);
}
but this one DOES execute in the main thread context.
The question extends to any thread that creates a timer this way; I thought a timer created in a thread executes the elapsed event in the same thread context. Am I missing something?
Quick edit: I see where these are different timers, System.Timers.Timer and Windows.Forms.Timer. So - how do I reliably create timers that will execute in the thread where I create them?
System.Timers,Windows.Forms.Timeris the second - Ňɏssa PøngjǣrdenlarpSystem.Threading.TimerandSystem.Windows.Threading.DispatcherTimertoo - Scott Chamberlain