Proper way of executing method in regular interval - c#

I want to execute the certain method of a class in regular interval when certain method is executed. C# has three methods I can use to furnish my needs. Since I am new to C# programming, I am confused in selecting the right method. Based on my study, the three classes are:
System.Windows.Forms.Timer
Systems.Timer
System.Diagnostics.StopWatch
My requirement is fairly simple: Execute the certain method at regular interval when the certain method is called.
Please suggest the situation where one is more preferred over others.

StopWatch is for measuring time, not for scheduling events, so let's rule that one out.
System.Windows.Forms.Timer is based on Windows Forms and requires the Windows message loop to run. Is your project Windows Forms, then you can use this. If not, do not use it (it won't work).
System.Timers.Timer is a general purpose timer. I would use this; it should work in all scenarios, you don't have to worry about the message loop running. You can also make this Timer synchronize automatically using it's SynchronizationObject property.
Finally, there is a System.Threading.Timer, which is not thread safe out of the box (meaning your method will get called on a worker thread, so if you need synchronization or dispatch on a specific thread due to UI, you will need to handle that yourself).
There are many subtle differences to these timers, I'd recommend you read the article Comparing the Timer Classes on MSDN for the full story.

Without knowing your specific use case, we can't tell you which is best. But in general:
System.Windows.Forms.Timer - Will call your function on the UI thread each time. Use this if you are planning to access UI controls during the event.
System.Timers.Timer - Will call your function on a worker thread. Use this in a context that is not Windows Forms or where you don't need to access any UI elements
System.Diagnostics.StopWatch - this is for timing how long things take. It won't help you here.
See: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

Related

Alternative to Timer

I'm developing a c# winform application which is based on third party web API's for trading purpose. It deals with real time data coming from internet like currency rates but I'm using 8 timer in my winform to retrieve different data, application gets non-responding because of timers,
what can i do to make this application work fast and smooth?
You might want to look into the System.Threading.Timer instead:
Timer Class
System.Threading.Timer, which executes a single callback method on a
thread pool thread at regular intervals. The callback method is
defined when the timer is instantiated and cannot be changed. Like the
System.Timers.Timer class, this class is intended for use as a
server-based or service component in a multithreaded environment; it
has no user interface and is not visible at runtime.
This link has a nice table of comparison between the different timer classes at the bottom:
Comparing the Timer Classes in the .NET Framework Class Library
Use threading. Timers (at least the ones you seem to be using) are executed in the GUI's thread. Use BackgroundWorkers (or other threading methods) instead to decouple background tasks from the GUI.

Why use Windows.Forms.Timer at all?

I read this excellent article Comparing the Timer Classes in the .NET Framework Class Library and came to the conclusion that anything I could do with Windows.Forms.Timer I can do better with Timers.Timer - and then some.
So the obvious question that comes to mind is: Why is the Windows.Forms Timer offered at all?
Legacy (backward compatibility) support?
Other?
The main convenience of the Windows.Forms.Timer is that its events are fired on the UI (Winforms) thread. If your timer events perform UI operations, it may be the simplest alternative (instead of calling Control.Invoke/BeginInvoke or SynchronizationContext.Post/Send inside all of your events).
The Windows.Forms.Timer events get invoked on the UI thread so you can update the UI from the event handlers directly, which is not normally the case with Timers.Timer (as you would get cross thread access violation exceptions).
And, as #Robert Harvey answered, it also has designer support.
One of advantage of Windows.Forms is that it run in the same thread of GUI and you do not get cross thread exceptions while accessing Form controls.
Windows.Forms.Timer has designer support. So it behaves like any other Winforms component (i.e. you can drag it onto a form, it's part of the Controls collection, etc).
Timer events raised by System.Windows.Forms.Timer class are synchronous with respect to the rest of the code in your Windows Forms app. This means that application code that is executing will never be preempted by an instance of this timer class (assuming you don't call Application.DoEvents). Events fired by the Windows.Forms.Timer class are compatible with your Winform controls; you can safely interact with them without having to call Invoke().
The System.Timers.Timer class is a server-based timer that was designed and optimized for use in multithreaded environments. Instances of this timer class can be safely accessed from multiple threads. Although Invoke() is technically required to interact with Winforms, the Timer class does provide a SynchronizingObject property, to which you can attach the Windows form with which you want to safely interact.
More here:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Well I think the answer is that they are two completely different types of timers. The Windows.Forms.Timer is a single-threaded application timer that's well suited for timers existing on the client running application.
A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
In contrast the Timers.Timer is a server-based timer that is better suited for Windows services.
The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.
You can find their documentation and read the excerpts and more from Microsoft.
It's not that one should never be used or always used, the serve two different purposes.
My belief is that it is for winform designer integration, in that you can drag it onto a form, click it and set its properties in the properties pane.

Methods to update GUI in WPF

I would like to ask what method to update GUI is better for my scenario.
I would like to manipulate (move) multiple controls from point to point based on the input from user's touches.
I know a few difference way to do it.
Dispatcher Timer & Timer. (What's the difference between them?)
BackgroundWorker.
Storyboard & BeginAnimation Method.
Which of these method is generally recommended to use in term of memory and resource saving and simpler to code?
Thank you!
I suppose these 3 SO QA should help u understand all the differences:
DispatcherTimer vs a regular Timer in WPF app for a task scheduler
Comparing Timer with DispatcherTimer
WPF BackgroundWorker vs. Dispatcher
Apart from the link given by Vijay, a common concept that is vital in WPF application while you manipulate visuals is Dispatcher
In short, a Dispatcher is a message queue gateway manager to the UI, that receives delegates and prioritises them to execute on the given thread. In WPF, UI thread is STA. Also any visual created on UI thread has a thread affinity which means if you are performing any multi threaded functionality (for faster performance) then when it comes to manipulating those visuals such as updating their values, increasing / deacresing their size, focusing them, transforming them etc. has to be done using the UI Dispatcher.
Now back to your situation, when you want to move items, translate transform animation is a good option.
Hope this helps you in correct direction.

Best practice for multiple long-methods using backgroundworker

I have a form that has many long-methods. My quest is: What is the best practice? Use anonymous method and only one backgroundworker or create an instance of BackgroundWorker to each long-method.
Please help. Thanks.
I would personnaly use one instance of BackgroundWorker for each of your tasks. However, keep in mind that you may call several times the same delegate method in multiple different instances of thread.
By having one BackgroundWorker per long-method task, you will have plenty control over your methods. Furthermore, as far as my understanding goes, once an instance of a BackgroundWorker performs a task, it is busy with this background task and therefore making it unavailable for others. I may perhaps be mistaken though, but that is anyway the way I would do it, as your DoWork() event handler can do only what it is asked to do for this BackgroundWorker. So, it seems impossible to me to perform totally different tasks for only one instance of BackgroundWorker.
Does this help?
In summary:
Advantages in one BackgroundWorker:
You control the order of the execution for the multiple method. However, this is also a disadvantage, because if you use multiple BackgroundWorkers, you "assume" they are executed parallely and not have to worry about the order;
Less overhead for thread creation and disposal (if possible, use same instance every time, but that's not always possible, depending on what starts the process. It's not possible if you want it to be done concurrently);
If you want to communicate between thread, you can accumulate a batch communication and do it more efficiently. Moreover, it may save you some of that communication if all methods are run in the same thread.
Advantages in multiple BackgroundWorkers:
The aforementioned parallelism;
Each end-of-process can use another delegate and therefore do some other operation.
Hope it helps!

what is the best approach for implementing a thread timer

What is the best approach in using a timer. Use a System.Timer.Timer class or use a single Thread in a non-terminating loop with a Thread.Sleep statement?
Thanks in advance
In general, use the components that are already there if they serve your needs. However, System.Threading.Timer uses the .NET thread pool, so any of the following conditions would make it a poor candidate:
You require a STA thread (all ThreadPool threads are MTA)
You require that all occurrences of your repeated task run on the same thread
You want to assign a particular priority (lower or higher) to your tasks
Your tasks are particularly long-running or utilize non-trivial blocks
Use a Timer. It's there, specifically for that purpose, so why wouldn't you use it?
The two methods you refer to are used for different results.
Timers will fire the event and invoke your method on a scheduled interval. They could invoke your method whilst another instance of it is running unless you stop the timer at the start of your processing (DoWork) and start it again when you're done (but then you might miss the timed events).
A method that loops and sleeps will not be invoked when it's busy. The "advantage" here is that you can DoWork, then find that the next timer event has already passed and DoWork immediately again. The alternative is that you have rest periods where you sleep a specified amount of time regardless of how long your DoWork method took.

Categories