Aishwarya Shiva Aishwarya Shiva - 1 year ago 111
C# Question

Timer vs. repetitive background worker

I am developing a Windows Forms application that calls a WCF service after a specified interval and shows output according to the data received from the service. I had a plan to use timer for this purpose that calls that WCF service method after 500 msec. But some of my colleagues told me to use background worker and then on

Work_Completed
event re-run the Worker. I want to know what is the difference between these two? Does timer also creates a background thread? Which one is best suited for long running tasks?

Answer Source

A Timer is almost certainly more suitable in terms of resource consumption. A BackgroundWorker is going to create a new thread just for that task. Creating a new thread is a fairly expensive operation. While there are many different timer implementations, and their implementations will vary, they are generally going to be reliant on OS tools that will fire an event periodically, which is going to be preferable to starting up a new dedicated thread.

Most of the key differences in Timer objects is what they do when they're "ready". Some create a new thread pool thread; some have a dedicated thread that is shared by all instances of the timer to run the handler(s), some marshal the code to the UI thread (or some other synchronization context) and it's the latter that you probably want. If you use the timer that is made available in the particular UI framework that you're using it's the behavior that you'll see.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download