Application is halting when using MethodInvoker in custom timer
-
19-06-2021 - |
Вопрос
Background:
I need a high resolution timer for an embedded system solution, so I decide to use MicroTimer from The Code Project...
BTW, I've developed a Windows Forms application to test its efficiency in such applications and for avoiding "cross-thread operation...", I have to use invocation methods, BackgroundWorker, etc. and decide to use this code:
private void btnMicorTimer_Click(object sender, EventArgs e)
{
// Instantiate new MicroTimer
MicroLibrary.MicroTimer microTimer = new MicroLibrary.MicroTimer();
// Add event handler
microTimer.MicroTimerElapsed +=
new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent);
// Call micro timer every 1000µs (1ms)
microTimer.Interval = 1000;
// Can choose to ignore event if late by Xµs (by default will try to catch up)
// microTimer.IgnoreEventIfLateBy = 500;
microTimer.Enabled = true; // Start timer
// Do something whilst events are happening. For demo sleep, 2000 ms (2 sec).
System.Threading.Thread.Sleep(2000);
microTimer.Enabled = false; // Stop timer
}
private void OnTimedEvent(object sender,
MicroLibrary.MicroTimerEventArgs timerEventArgs)
{
string response = string.Format(
"Count = {0:#,0} Timer = {1:#,0} µs | " +
"LateBy = {2:#,0} µs | ExecutionTime = {3:#,0} µs",
timerEventArgs.TimerCount, timerEventArgs.ElapsedMicroseconds,
timerEventArgs.TimerLateBy, timerEventArgs.CallbackFunctionExecutionTime);
// Do something small that takes significantly less time than Interval
if (listBox1.InvokeRequired)
{
Invoke(new MethodInvoker(
delegate
{
listBox1.Items.Add(response);
}));
}
else
listBox1.Items.Add(response);
}
Problem:
As said before, the application is halting immediately after a button is pressed! Briefly this is what happens after btnMicorTimer_Click :( It's look like the project is trapped in an infinite loop.
Решение
The peak you see can easily be explained:
You are requesting a UI update every millisecond by adding an item to the listbox.
That will slow down the response of the UI considerably.