What happens while using System.Threading.Timer? - c#

I am a newbie to dotnet, and I have a C# code in a Windows Service application which have to run for every 24hours. For specifying the interval I used the below code:
var t=new System.Threading.Timer(e=>method(),null,Timespan.Zero,TimeSpan.FromHours(24));
So the above line of code would check for the condition for every 24 hours.
My doubt is, what happens to the process in the mean time(like between 24 hours). Does it goes to sleep on its own? if so, is there any way to know if the process is at sleep

Does it goes to sleep on its own?
No, the current thread will continue to run, and do whatever you tell it to do. If you want the thread to sleep you need to tell it to sleep. And this is possibly what you should do for a console program, or trap it in a "press any key to continue" question.
If your application is an UI application there will be a main thread that listens for windows messages, in that case you should rarely if ever use Thread.Sleep on the UI thread.
The timer uses the OS to do the actual waiting, and this will eventually use some kind of hardware to raise timing events. When the timer elapses it will raise the event on the threadpool, so it may run concurrently with the thread that started the timer. Note that there are other timers that work slightly differently.

Related

.NET Scheduling many operations: single timer vs one timer for operation

I am developing a Windows Service application, in .NET, which executes many functions (it is a WCF service host), and one of the targets is running scheduled tasks.
I chose to create a System.Threading.Timer for every operation, with a dueTime set to the next execution and no period to avoid reentrancy.
Every time the operation ends, it changes the dueTime to match the next scheduled execution.
Most of the operations are scheduled to run every minute, not all toghether but delayed by some seconds each other.
Now, after adding a number of operations, about 30, it seems that the timers start to be inaccurate, starting the operations many seconds late, or even minutes late.
I am running the operation logic directly in the callback method of the timer, so the running thread should be the same as the timer.
Should I create a Task to run the operation instead of running it in the callback method to improve accuracy?
Or should I use a single timer with a fixed (1 second) dueTime to check which operations need to be started?
I don't like this last option because it would be more difficult to handle reentrancy..
Timers fire on a thread pool thread, so you are probably finding that as you add lots of timers that you are exhausting the thread pool.
You could increase the size of the thread pool, or alternatively ensure you have fewer timers than the thread pool size.
Firing off Tasks from the callback likely won't help - since you are going to be fighting for threads from the same thread pool. Unless you use long-running tasks.
We usually setup multiple timers to handle different actions within a single service. We set the intervals and start, stop the timer on the Service Start/Stop/Shutdown events (and have a variable indicating the status for each one, i.e. bool Stopped)
When the timer ticks over, we stop the timer, run the processing (which may take a while depending on the process, i.e. may take longer than the interval if its short.. (this code needs to be in a try--catch so it keeps going on errors)
After the code has processed, we check the Stopped variable and if its not stopped we start the timer again (this handles the reentrancy that you've mentioned and allows the code to stick to the interval as much as possible)
Timers are generally more accurate after about 100ms as far as I know, but should be close enough for what you want to do.
We have run this concept for years, and it hasn't let us down.
If you running these tasks as a sub-system of an ASP.NET app, you should also look at HangFire, which can handle background processing, eliminating the need for the windows service.
How accurate do the timers need to be? you could always use a single timer and run multiple processing threads at the same time? or queue the calls to some operations if less critical.
Ok, I came to a decision: since I am not able to easily reproduce the behavior, I chose to solve the root problem and use the Service process to only:
serve WCF requests done by clients
schedule operations (which was problematic)
Every operation that could eat CPU is executed by another process, which is controlled directly by the main process (with System.Diagnostics.Process and its events) and communicates with it through WCF.
When I start the secondary process, I pass to it the PID of the main process through command line. If the latter gets killed, the Process.Exited event fires, and I can close the child process too.
This way the main service usually doesn't use much CPU time, and is free to schedule happily without delays.
Thanks to all who gave me some advices!

What are the differences between System.Threading.Timer and creating your own background tick thread in C#

I have a background tick function that is structured as follows:
System.Threading.Thread myTimerThread = new Thread(this.Tick);
private void Tick(){
do{
//do stuff
System.Threading.Sleep(1000L);
}while(true)
}
However, there is also a System.Threading.Timer class that does this for me. What are the differences in using the built in Timer class present in System.Threading rather than creating my own background thread with a Tick function?
The Timer class would be very light weight and more efficient as compared to your own dedicated thread which is sleeping for a specified time inside infinite do while loop.
Do read Thread.Sleep is a sign of a poorly designed program for finding out how Thread.Sleep actually works and how it wastes a complete thread and resources
On the other hand System.Threading.Timer will use ThreadPool thread to execute the timer. Other benefit of using Timer class as described my MSDN
When you create a timer, you can specify an amount of time to wait before the
first execution of the method (due time), and an amount of time to wait between
subsequent executions (period). You can change these values, or disable the timer, using the Change method.
You won't have these benefits in thread based approach
First of all, use the thread pool unless you are performing a long running operation. The difference between your roll your own timer, and System.Threading.Timer is that System.Threading.Timer uses hardware interrupts to know when it is appropriate to perform the tick. It will be more accurate (though a multimedia timer will be even more accurate) than just sleeping for x milliseconds which will have to wait until control is given thread scheduler before your thread will have control.
You should also know that if you are doing anything that will affect the Gui on your thread you should use the appropriate Gui version of the timer otherwise your ticks will not occur on the thread you have to access Gui controls on and you will have to Invoke to get on the correct thread. For windows forms it is System.Windows.Forms.Timers, it is System.Windows.Threading.DispatcherTimer for WPF and Silverlight. For more information on threading and timers I highly recommend Joseph Albahari's free ebook Threading in C#.
You have alot more control using System.Threading.Timer. You can program the timer to check a certain thread or event every say....1/4 of a second, until it runs and then you can dispose of the timer using the dispose method. Its a lot more flexible because you can program it to do whatever you want and it is a lot more accurate.
When you use Thread.Sleep, you really only have one option and that is to force the program to "sleep" for x of seconds. To my knowledge you can not dispose it, time it, coordinate it so it stops early. etc. The bottom line is, even after your program is done running, the Thread.Sleep will continue to force the program to sleep. Threading.Timer can be programmed to stop when the program is finished running.

Best practice for continual running process in C#

I am working on a project in C#.NET using the .NET framework version 3.5.
My project has a class called Focuser.cs which represents a physical device, a telescope focuser, that can communicate with a PC via a serial (RS-232) port. My class (Focuser) has properties such as CurrentPosition, CurrentTemperature, ect which represents the current conditions of the focuser which can change at any time. So, my Focuser class needs to continually poll the device for these values and update its internal fields. My question is, what is the best way to perform this continual polling sequence? Occasionally, the user will need to switch the device into a different mode which will require the ability to stop the polling, perform some action, and then resume polling.
My first attempt was to use a time that ticks every 500ms and then calls up a background worker which polls for one position and one temperature then returns. When the timer ticks if the background worker isBusy then it just returns and tries again 500ms later. Someone suggested that I get rid of the background worker all together and just do the poll in the timer tick event. So I set the AutoReset property of the timer to false and then just restart the timer every time a poll finishes. These two techniques seemed to behave the exact same way in my application so I am not sure if one is better than the other. I also tried creating a new thread every time I want to do a poll operation using a new ThreadStart and all that. This also seemed to work fine.
I should mention one other thing. This class is part of a COM object server which basically means that the class library that is produced will be called upon via COM. I am not sure if this has any influence on the answer but I just thought I should throw it out there.
The reason I am asking all of this is that all of my test harness runs and debug builds work just fine but when I do a release build and try to make calls to my class from another application, that application freezes up and I am having a hard time determining the cause.
Any advice, suggestions, comments would be appreciated.
Thanks, Jordan
Remember that the timer hides its own background worker thread, which basically sleeps for the interval, then fires its Elapsed event. Knowing that, it makes sense just to put the polling in Elapsed. This would be the best practice IMO, rather than starting a thread from a thread. You can start and stop Timers as well, so the code that switches modes can Stop() the Timer, perform the task, then Start() it again, and the Timer doesn't even have to know the telescope IsBusy.
However, what I WOULD keep track of is whether another instance of the Elapsed event handler is still running. You could lock the Elapsed handler's code, or you could set a flag, visible from any thread, that indicates another Elapsed() event handler is still working; Elapsed event handlers that see this flag set can exit immediately, avoiding concurrency problems working with the serial port.
So it looks like you have looked at 2 options:
Timer. The Timer is non-blocking while waiting (uses another thread), so the rest of the program can continue running and be responsive. When the timer event kicks off, you simply get/update the current values.
Timer + BackgroundWorker. The background worker is also simply a separate thread. It may take longer to actually start the thread than to simply get the current values. Unless it takes a long time to get the current values and causes your program to become unresponsive, this is unnecessary complexity.
If getting values is fast enough, stick to #1 for simplicity.
If getting values is slow, #2 will work but unnecessarily has a thread start a thread. Instead, do it with only a BackgroundWorker (no Timer). Create the BackgroundWorker once and store in a variable. No need to recreate it every time. Make sure to set WorkerSupportsCancellation to true. Whenever you want to start checking values, on your main program thread do bgWorker.RunWorkerAsync(). When you want to stop, do bgWorker.CancelAsync(). Inside your DoWork method, have a loop that checks the values and does a Thread.Sleep(500). Since it's a separate thread, it won't make your program unresponsive. In the loop conditions, also check to see if the polling was cancelled and break out. You'll probably need a way to get the values back to the main thread. You can use ReportProgress() if an integer is good enough. Otherwise you can create an object to hold the content, but make sure to lock (object) { } before reading and modifying it. This is a quick summary, but if you go this route I would recommend you read: http://www.albahari.com/threading/part3.aspx#_BackgroundWorker
Is the process of contacting the telescope and getting the current values actually take long enough to warrant polling? Have you tried dropping the multithreading and just blocking while you get the current value?
To answer your question, however, I would suggest not using a background worker but an actual Thread that updates the properties continuously.
If all these properties are read only (can you set the temp of the telescope?) and there are no dependencies between them (e.g., no transactions are required to update multiple properties at once) you can drop all the blocking code and let your thread update willy-nilly while other threads access the properties.
I suggest a real, dedicated Thread rather than the thread pool just because of a lack of knowledge of what might happen when mixing background threads and COM servers. Also, apartment state might play into this; with a Thread you can try STA but you can't do that with a threadpool thread.
You say the app freezes up in a release build?
To eliminate extra variables, I'd take all the timer/multi-threaded code out of the application(just comment it out), and try it with a straightforward blocking method.
i.e. You click a button, it calls a function, that function hits the COM object for data, and then updates the UI. All in a blocking, synchronous fashion. This will tell you for sure whether it's the multi-threading code that's freezing you up, or if it's the COM interaction itself.
How about starting a background thread with ThreadPool? Then enter a loop based on a bool (While (bContinue)) that loops and does your work and then a Thread.Sleep at the end of the loop - exiting the program would include setting bContinue to false so the thread stops - perhaps hook it up to the OnStop event in a windows service
bool bRet = ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc));
private void ThreadFunc(object objState)
{
// enter loop
bContinue = true;
while (bContinue) {
// do stuff
// sleep
Thread.Sleep(m_iWaitTime_ms);
}
}

System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks

In my application I have to send periodic heartbeats to a "brother" application.
Is this better accomplished with System.Timers.Timer/Threading.Timer or Using a Thread with a while loop and a Thread.Sleep?
The heartbeat interval is 1 second.
while(!exit)
{
//do work
Thread.Sleep(1000);
}
or
myTimer.Start( () => {
//do work
}, 1000); //pseudo code (not actual syntax)...
System.Threading.Timer has my vote.
System.Timers.Timer is meant for use in server-based (your code is running as a server/service on a host machine rather than being run by a user) timer functionality.
A Thread with a While loop and Thread.Sleep command is truly a bad idea given the existance of more robust Timer mecahnisms in .NET.
Server Timers are a different creature than sleeping threads.
For one thing, based on the priority of your thread, and what else is running, your sleeping thread may or may not be awoken and scheduled to run at the interval you ask. If the interval is long enough, and the precision of scheduling doesn't really matter, Thread.Sleep() is a reasonable choice.
Timers, on the other hand, can raise their events on any thread, allowing for better scheduling capabilities. The cost of using timers, however, is a little bit more complexity in your code - and the fact that you may not be able to control which thread runs the logic that the timer event fires on. From the docs:
The server-based Timer is designed for
use with worker threads in a
multithreaded environment. Server
timers can move among threads to
handle the raised Elapsed event,
resulting in more accuracy than
Windows timers in raising the event on
time.
Another consideration is that timers invoke their Elapsed delegate on a ThreadPool thread. Depending on how time-consuming and/or complicated your logic is, you may not want to run it on the thread pool - you may want a dedicated thread. Another factor with timers, is that if the processing takes long enough, the timer event may be raised again (concurrently) on another thread - which can be a problem if the code being run is not intended or structured for concurrency.
Don't confuse Server Timers with "Windows Timers". The later usually refers to a WM_TIMER messages tha can be delivered to a window, allowing an app to schedule and respond to timed-processing on its main thread without sleeping. However, Windows Timers can also refer to the Win API for low-level timing (which is not the same as WM_TIMER).
Neither :)
Sleeping is typically frowned upon (unfortunately I cannot remember the particulars, but for one, it is an uninteruptible "block"), and Timers come with a lot of baggage. If possible, I would recommend System.Threading.AutoResetEvent as such
// initially set to a "non-signaled" state, ie will block
// if inspected
private readonly AutoResetEvent _isStopping = new AutoResetEvent (false);
public void Process()
{
TimeSpan waitInterval = TimeSpan.FromMilliseconds (1000);
// will block for 'waitInterval', unless another thread,
// say a thread requesting termination, wakes you up. if
// no one signals you, WaitOne returns false, otherwise
// if someone signals WaitOne returns true
for (; !_isStopping.WaitOne (waitInterval); )
{
// do your thang!
}
}
Using an AutoResetEvent (or its cousin ManualResetEvent) guarantees a true block with thread safe signalling (for such things as graceful termination above). At worst, it is a better alternative to Sleep
Hope this helps :)
I've found that the only timer implementation that actually scales is System.Threading.Timer. All the other implementations seem pretty bogus if you're dealing with a non trivial number of scheduled items.

C# Windows Service Intermittent Method Call

Scenario
I have a C# Windows Service that essentially subscribes to some events and if anything is triggered by the events, it carries out a few tasks.
The Thing...
....is that these events are monitoring processes, which I need to restart at certain times of the day.
Question
What's the best way I can go about performing this task at an exact time?
Thoughts so far are:
1)To use a timer that checks what time it is every few minutes.
2)Something that isn't a timer and doesn't suck as an implementation.
Help greatly appreciated.
Start a new thread at service start with IsBackground = true. This ensures your thread dies when your service stops, so you can simply start and forget it.
In the thread, use an endless loop with Thread.Sleep(60*1000)'s, waiting for the correct time of day to do the restart. The restart should probably be done on a new thread with IsBackground = false to prevent your service from stopping before your app is finished restarting (restricted to 30 secs or so permitted by Windows for your service to shut down). Alternatively you can spawn a separate process for the restart operation.
You could set off timers that run at particular times of the day but I would probably favour the following approach.
while (!closing)
{
if (SomethingNeedsDoingNow()) { DoIt(); }
Thread.Sleep(1);
}
This will barely consume any resources and will then be able to fire off events at any time of the day to a 1 second granularity easily.
Note SomethingNeedsDoingNow should check the current time, and see if any events need firing. If you can get away with a looser granularity then you can sleep for 60seconds instead.
One option, if you really want to avoid implementing a timer, is a windows scheduled task that kills your processed when it's fired.
You can then have your service constantly polling to make sure the processes are running, and if not start them.
Still kind of 'timer-y' granted, but it's another approach.

Categories

Resources