Which .Net Timer() to use

前端 未结 5 1431
一向
一向 2020-12-09 22:27

I have a legacy WinForms Mdi App in VB.Net 2.0 which I am adding functionality to. One of the additions is a warning which needs to be raised when the current time nears a s

相关标签:
5条回答
  • 2020-12-09 22:52

    The System.Forms.Timer actually works on the main thread using the windows message queue. This makes it somewhat inacurate but since you don't really need ms precision it's good enough. You could use one of the other timers that work on a separate thread but since you need to activate a winforms component that work in the main you'll need to use Form.Invoke or some other way to pass the event to the main thread - which would cause some latency as well. In conclusion use the System.Forms.Timer when you need to activate a winforms based component.

    0 讨论(0)
  • 2020-12-09 22:54

    I would just use the Forms timer. I think I read that it's not as accurate, but it sounds like you don't need it to be.

    0 讨论(0)
  • 2020-12-09 23:07

    I agree that Windows.Forms.Timer() is the best for this case as it handles the cross thread marshalling issues.

    Some useful related links:

    • Windows Presentation Foundation Threading Model
    • WinForms UI Thread Invokes: An In-Depth Review of Invoke/BeginInvoke/InvokeRequred
    0 讨论(0)
  • 2020-12-09 23:07

    Ok, first things first...

    If you want to show the user a form and do something in the background I would use the BackgroundWorker class, it worked for me before. Also, you need invoke methods as mentioned before and as Chris said, it sounds harder than what it actually is.

    Here's a link which I think will help you out.
    http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx

    0 讨论(0)
  • 2020-12-09 23:12

    This article explains pretty well:

    Comparing the Timer Classes in the .NET Framework Class Library

    It sounds like System.Windows.Forms.Timer is the one for you.

    My guideline: If you want the timer to run on your main GUI thread, stick with Windows.Forms.Timer. If it's okay for your timer to be called asynchronously on a thread pool thread, or if you don't want to experience the small delays that System.Windows.Forms.Timer tends to suffer, use System.Timers.Timer. System.Threading.Timer has a different interface from the other two and is not thread-safe; personally, I'm not a fan.

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