System.Timers.Timer hangs the Windows Forms application in c#

前端 未结 2 1017
逝去的感伤
逝去的感伤 2021-01-28 03:49

The code below shows a timer that ticks every 100* 1000(milliseconds) to show a pop up message for registration.The below code is working but unfortunately my application gets h

相关标签:
2条回答
  • 2021-01-28 04:41

    The application hangs because you're doing a popup (I assume a MessageBox or some other modal dialog box). Of course the application is going to hang. You're putting a modal dialog up in the UI thread.

    The problem isn't with the timer, but with your application design.

    0 讨论(0)
  • 2021-01-28 04:44
        register_Timer.SynchronizingObject = this; 
    

    This completely defeats the reason for using System.Timers.Timer. It prevents the Elapsed event handler from being raised on a threadpool thread, the property ensures it will run on the UI thread. Which is what you wanted.

    But you still get all the disadvantages of that Timer class. Particularly its habit for swallowing exceptions without a diagnostic is very ugly. As well as continuing to raise the Elapsed event after the form is closed, ensuring this cannot happen is a very difficult problem to solve, there are two inherent race conditions. .NET 1.0 had some design mistakes related to threading, this was one of them.

    Just don't do this, use a System.Windows.Forms.Timer instead. It will work exactly like your timer, minus all the disadvantages.

    0 讨论(0)
提交回复
热议问题