Where can I find a good C# console app that demonstrates polling? - c#

I'm looking for a good example of polling in C#.
Basically, every X seconds an instrument is read and the values logged to a text file. I was looking for a sample that makes use of .NET 4's parallel library. Or, maybe I'm overthinking this solution by looking at TPL...
ps- this question is unrelated to my previous question about database polling.

I'm not sure I'd particularly bother with TPL here. Just use System.Threading.Timer or System.Timers.Timer to perform an action periodically. Those will both use the thread pool - what are you planning on doing in the main console thread during this time?
Of course, another extremely simple option would be to just make the main thread sleep between poll occurrences. It's crude, but if that's all your app needs to do, it may well be good enough for you. I'm not sure how it behaves if the system clock is changed, mind you... is this for a very long-running task for production usage, or just a quick tool? (If it's a long-running app, you might want to consider using a Windows Service instead.)

It's real easy to create a timer:
static void Main(string[] args)
{
// Create a timer that polls once every 5 seconds
var timer = new System.Threading.Timer(TimerProc, null, 5000, 5000);
Console.WriteLine("Polling every 5 seconds.");
Console.WriteLine("Press Enter when done:");
Console.ReadLine();
timer.Dispose();
}
static int TickCount = 0;
static void TimerProc(object state)
{
++TickCount;
Console.WriteLine("tick {0}", TickCount);
}
Note that the TimerProc is called on a separate thread. Your main program can do other things, and this will continue to poll every five seconds until you kill (or modify) the timer.
I prefer System.Threading.Timer over System.Timers.Timer because the latter swallows exceptions. If there is a bug in your elapsed event handler that throws an exception, you'll never know about it because the System.Timers.Timer event handler will suppress the exception. For that reason, I strongly suggest that you not use it. Use System.Threading.Timer instead.

Using the PL doesn't sound correct to me for this task. I recommend checking out System.Timer with which you can specify a recurring interval at which the Elapsed event is raised in your application allowing you to handle the event to perform regular processing.

Related

Why using System.Threading.Thread.Sleep() is a bad practice?

I'm writing an application working with a big and ugly 3rd party system via a complicated API.
Sometimes some errors happen in the system, but if we wait for my program to face this errors it can be too late.
So, I use a separate thread to check the system state as following:
while (true)
{
ask_state();
check_state();
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
}
It doesn't really matter if I check the system state once in 100 ms or once a minute.
But I have heard that using Thread.Sleep() is a bad practice. Why? And what can I do in this situation?
One reason is that Thread.Sleep() is blocking your code from doing anything else. Recent efforts is to make blocking as least as possible. For example, node.js is a non-blocking language.
Update: I don't know about the infrastructure of Timer class in C#. Maybe it's also blocking.
You can schedule a task to check that third API every 100 ms. This way, during that 100 ms, your program can do other tasks.
Update: This analogy might help. If we compare operating system to a hospital, and compare the threads to nurses in that hospital, the supervisor (programmer) can choose a policy:
Either to ask each nurse (thread) to watch one, and only one patient (a job, a task to be done), even if between each check she waits for an hour (Sleep() method)
To ask each nurse to check each patient, and during the interval till next check, go on and check other patients.
The first model is blocking. It's not scalable. But in the second model, even with few nurses, you might be able to serve many patients.
Because the only way to shut down this thread if it's waiting inside the Sleep is to either a) wait for the Sleep to end, or b) use one of Thread.Abort or Thread.Interrupt.1
If it's a long sleep, then (a) isn't really suitable if you're trying to be responsive. And (b) are pretty obnoxious if the code happens to not actually be inside the Sleep at the time.
It's far better, if you want to be able to interrupt the sleeping behaviour in a suitable fashion, to use a waitable object (such as e.g. a ManualResetEvent) - you might then even be able to place the wait on the waitable object into the while conditional, to make it clear what will cause the thread to exit.
1 I've use shutdown in this instance because it's a very common scenario where cross-thread communication is required. But for any other cross-thread signalling or communication, the same arguments can also apply, and if it's not shutdown then Thread.Abort or Thread.Interrupt are even less suitable.
i would set a timer to whatever ms you want and wait for my check methods to complete, by the way do you want to use an eternal loop or it is not a complete code that you showed up there ?
ok this is a sample of what i'm talking about:
public void myFunction()
{
int startCount = Environment.TickCount;
ask_state();
check_state();
while (true)
{
if (Environment.TickCount - startCount >= 20000) //two seconds
{
break;
}
Application.DoEvents();
}
}
//Now you have an organized function that makes the task you want just call it every
// time interval, again you can use a timer to do that for you
private void timer_Tick(object sender, EventArgs e)
{
myFunction();
}
good luck

Single threaded timer and/or interval inside a Task<T>

I want to run a function on an interval, inside of a Task. Something like,
Task t = Task.Factory.StartNew(() => {
while (notCanceled()) {
doSomething();
Thread.Sleep(interval);
}
});
Is it a bad idea to use Thread.Sleep() here? The task is long running, and the sleep time may also be very long (minutes, maybe even hours).
One alternative is to use either System.Timers.Timer or System.Threading.Timer. However both of these would cause an additional thread to spawn (the Elapsed events occur on a new threadpool thread). So for every repeating task, there would be 2 threads instead of 1. The Task is already asynchronous so I'd prefer not to complicate things in this way.
Yet another way that behaves similarly is to use ManualResetEvent,
ManualResetEvent m = new ManualResetEvent(false);
void sleep(int milliseconds)
{
m.WaitOne(milliseconds);
}
Since m.Set() would never be called, this would always wait for the right amount of time, and also be single threaded. Does this have any significant advantage over Thread.Sleep()?
Wondering what the best practice would be here.
Thoughts?
If you're using C# 5.0 you can use:
while(notCanceled())
{
doSomething();
await Task.Delay(interval);
}
If you're using an earlier version your best bet is probably to use a Timer.
Both of the code samples you showed, involving either Thread.Sleep or a ManualResetEvent are blocking the current thread for that duration, which means your code is tying up a thread which can't do anything else until your task is canceled. You don't want to do that. If you use a timer, or the await code mentioned above, you will end up not blocking any thread at all while waiting, and then use up a thread pool's time only when you have productive work to be doing.
Yes, it is a very bad idea to use sleep in a loop like that.
You have a faulty understanding of timers. Creating a timer does not create a new thread. The timer sets an operating system trigger that, when the time elapses, spawns a threadpool thread. So if you write:
System.Threading.Timer myTimer =
new Timer(DoStuff, null,
TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
The only time there will be another thread is when the handler method (DoStuff) is executing.
There'd be no reason to have the task if everything it does is handled by your DoStuff method. If you want to cancel it, just dispose the timer.
I strongly recommend, by the way, that you not use System.Timers.Timer. In short, it squashes exceptions, which hides bugs. See Swallowing exceptions is hiding bugs.

how to recalculate something ~once per second?

I need to do some pretty fast recalculation ~every second.
What is the best way to do that? Is using dedicated thread and Thread.Sleep is ok?
Task.Factory.StartNew(() =>
{
while (true)
{
RecalculateState();
Thread.Sleep(1000);
}
}, TaskCreationOptions.LongRunning);
That would work - but another alternative would be to use a timer, e.g. System.Threading.Timer or System.Timers.Timer.
You should think about:
What do you want to happen if it takes more than a second to recalculatte state?
Is your RecalculateState method entirely safe to be called from arbitrary threads?
You can use System.Timers.Timer with 1 second interval.
It already runs in a new thread .
Pay attention on fact, that if RecalculateState runs longer than expected interval (for 1000 of reasons) you have to deal with calls overlapping, so you have to manage that case in some way.
One of possible solutions, is to run a new code only after execution of the method finished, and measure difference between execution time and interval. But this is not so easy task to do. Fortunatelly someone already thought about that problem.
Can have a look on Reactive Extensions that in latest build payed special attention on time dependent execution.
Can't you use a timer and make a ontimed event?
Something like this ?
Observable.Timer(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(1)).Timestamp()
.Subscribe(MyOnTimedEventMethod);
I would suggest to use a timer for this.
member:
private readonly Timer _timer;
instantiate the timer in the constructor for instance:
_timer= new Timer(OnTimerEllapsed, null, 0, 1000);
callback:
private void OnTimerEllapsed(object sender)
{
RecalculateState();
}

Best practice for an endless/ periodic execution of code in C#

Often in my code I start threads which basically look like this:
void WatchForSomething()
{
while(true)
{
if(SomeCondition)
{
//Raise Event to handle Condition
OnSomeCondition();
}
Sleep(100);
}
}
just to know if some condition is true or not (for example if a have a bad coded library with no events, just boolean variables and I need a "live-view" of them).
I wonder if there is a better way to accomplish this kind of work like a Windows function to hook in which can run my methods all x sec. Or should I code a global event for my app, raising all x secs and let him call my methods like this:
//Event from Windows or selfmade
TicEvent += new TicEventHandler(WatchForSomething));
and then this method:
void WatchForSomething()
{
if(SomeCondition)
{
//Raise Event to handle Condition
OnSomeCondition();
}
}
So, I hope this is not closed because of being a "subjective question" or something, I just want to know what the best practice for this kind of work is.
There isn't necessarily a "best way" to write long-running event processing code. It depends on what kind of application you are developing.
The first example you show is the idiomatic way in which you would often see the main method of a long-running thread written. While it's generally desirable to use a mutex or waitable event synchronization primitive rather than a call to Sleep() - it is otherwise a typical pattern used to implement event processing loops. The benefit of this approach is that it allows specialized processing to run on a separate thread - allowing your application's main thread to perform other tasks or remain responsive to user input. The downside of this approach is that it may require the use of memory barriers (such as locks) to ensure that shared resources are not corrupted. It also makes it more difficult to update your UI, since you must generally marshal such calls back to the UI thread.
The second approach is often used as well - particularly in systems that already have an event-drive API such as WinForms, WPF, or Silverlight. Using a timer object or Idle event is the typical manner in which periodic background checks can be made if there is no user-initiated event that triggers your processing. The benefit here is that it's easy to interact and update user interface objects (since they are directly accessible from the same thread) and it's mitigates the need for locks and mutexes to protected data. One potential downside of this approach is if the processing that must be performed is time-consuming it can make your application unresponsive to user input.
If you are not writing applications that have a user interface (such as services) then the first form is used much more often.
As an aside ... when possible, it's better to use a synchronization object like an EventWaitHandle or Semaphore to signal when work is available to be processed. This allows you to avoid using Thread.Sleep and/or Timer objects. It reduces the average latency between when work is available to be performed and when event processing code is triggered, and it minimizes the overhead of using background threads, since they can be more efficiently scheduled by the runtime environment and won't consume any CPU cycles until there's work to do.
It's also worth mentioning that if the processing you do is in response to communications with external sources (MessageQueues, HTTP, TCP, etc) you can use technologies like WCF to provide the skeleton of your event handling code. WCF provides base classes that make it substantially easier to implement both Client and Server systems that asynchronously respond to communication event activity.
If you have a look at Reactive Extensions, it provides an elegant way of doing this using the observable pattern.
var timer = Observable.Interval(TimeSpan.FromMilliseconds(100));
timer.Subscribe(tick => OnSomeCondition());
A nice thing about observables is the ability to compose and combine further observables from existing ones, and even use LINQ expressions to create new ones. For example, if you wanted to have a second timer that was in sync with the first, but only triggering every 1 second, you could say
var seconds = from tick in timer where tick % 10 == 0 select tick;
seconds.Subscribe(tick => OnSomeOtherCondition());
By the way, Thread.Sleep is probably never a good idea.
A basic problem with Thread.Sleep that people are usually not aware of, is that the internal implementation of Thread.Sleep does not pump STA messages. The best and easiest alternative, if you have to wait a given time and can't use a kernel sync object, is to replace Thread.Sleep with Thread.Join on the current thread, with the wanted timeout. Thread.Join will behave the same, i.e. the thread would wait the wanted time, but in the meantime STA objects will be pumped.
Why this is important (some detailed explanatiopn follows)?
Sometimes, without you even knowing, one of your threads may have created an STA COM object. (For example this sometimes happens behind the scenes when you use Shell APIs). Now suppose a thread of yours has created an STA COM object, and is now in a call to Thread.Sleep.
If at sometime the COM object has to be deleted (which can happen at an unexpected time by the GC), then the Finalizer thread will try calling the object's distruvtor. This call will be marshalled to the object's STA thread, which will be blocked.
Now, in fact, you will have a blocked Finalizer thread. In this situations objects can't be freed from memory, and bad things will follow.
So the bottom line: Thread.Sleep=bad. Thread.Join=reasonable alternative.
The first example you show is a rather inelegant way to implement a periodic timer. .NET has a number of timer objects that make this kind of thing almost trivial. Look into System.Windows.Forms.Timer, System.Timers.Timer and System.Threading.Timer.
For example, here's how you'd use a System.Threading.Timer to replace your first example:
System.Threading.Timer MyTimer = new System.Threading.Timer(CheckCondition, null, 100, 100);
void CheckCondition(object state)
{
if (SomeCondition())
{
OnSomeCondition();
}
}
That code will call CheckCondition every 100 milliseconds (or thereabouts).
You don't provide a lot of background on why you're doing this, or what you're trying to accomplish, but if its possible, you might want to look into creating a windows service.
Use a BackgroundWoker for additional thread safe measures:
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
.
.
.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (;;)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(100);
}
}
}
For more info visit: http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx
A very simple way for non blocking wait other threads/tasks is:
(new ManualResetEvent(false)).WaitOne(500); //Waits 500ms

Using C# Timer to stop executing a Program

I want a program to stop executing for a certain amount of time. And i want this to happen in regular intervals. For example, i want a program to run for 5 minutes and then it should stop for 2 mintues and continue running for another 5 minutes after that. Is this possible with the C# Timer class?
You're looking for Thread.Sleep() passing in the number of milliseconds to pause execution for.
I'm not sure this is desirable behaviour, so if you update your question you might get a better answer than this.
You can use a timer that does little more than toggle a variable (e.g. bool). If that bool is used by the application, then you can use it to control whether the application is "running".
I'm suggesting this instead of Thread.Sleep() because at least your application is still responsive. If you want to pause a non-UI thread, then Thread.Sleep() will suffice, but don't call Thread.Sleep() on the UI thread, even with very short durations.
As previous answer say: what is 'stop'? The user can't use the program for 2 minutes? If so you could pop a modal dialog (with text) and the user can't close it.
If this is a Windows Forms application, you might want to consider moving this into a threaded execution model. You can do this using either the BackgroundWorker control, thread pooling with the ThreadPool class, asynchronous methods Begin and End (such as Stream.BeginWrite), or by manually handling the thread yourself (bit more complex).
A BackgroundWorker will provide the easiest form of development by allowing you to handle events for the asynchronous code, and update a progress bar or label to show the current state of the execution. This will allow you to use Thread.Sleep without the system warning the user that the application has hung.
Basically, in Windows Forms development you should be using some form of threading to handle long executions.
You can use Window.Forms.Timer to register a callback each 1000ms
private int counter;
void StartTimer()
{
counter = 0;
Timer timer = new Timer();
timer.Interval = 1000;
timer.Enabled = true;
timer.Tick += Timer_Tick;
}
In the event function simply increment a global counter variable that executes when
a condition fulfills
private void Timer_Tick(object sender, EventArgs e)
{
counter++;
}

Categories