简体   繁体   English

在自定义计时器中使用MethodInvoker时,应用程序停止

[英]Application is halting when using MethodInvoker in custom timer

Background: 背景:

I need a high resolution timer for an embedded system solution, so I decide to use MicroTimer from The Code Project ... 我需要一个用于嵌入式系统解决方案的高分辨率计时器,因此我决定使用The Code Project中的 MicroTimer ...

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: 顺便说一句,我已经开发了一个Windows Forms应用程序来测试其在此类应用程序中的效率并避免“跨线程操作...” ,我必须使用调用方法,BackgroundWorker等,并决定使用以下代码:

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. 简而言之,这是在btnMicorTimer_Click之后发生的事情:(看起来项目陷入了无限循环。

The peak you see can easily be explained: 您看到的峰值很容易解释:

You are requesting a UI update every millisecond by adding an item to the listbox. 您正在通过将项目添加到列表框中来请求每毫秒的UI更新。

That will slow down the response of the UI considerably. 这将大大减慢UI的响应速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM