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

前端 未结 2 1016
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题