One timer, many method calls or many timers, one method call? - c#

I'm developing an application for WinCE 5.0 on .NET CF 2.0.
I was wondering what other people see as the best solution in the following two cases:
Assume that i have 10 methods that i need to run every 50mS.
Solution 1:
Create one System.Threading.Timer that runs every 50mS and then in this callback run the above mentioned 10 methods.
Solution 2:
Create 10 System.Threading.Timer that runs every 50mS and then in each of their callbacks call one of the above methods.
Which solution do you think is best? Some of the methods are cpu intensive, others are not.

Using multiple timers makes the calls independent. That matters most with respect to exceptions. Do you want the other methods to proceed if #2 throws? Are the methods otherwise dependent on each other?
With multiple timers on a multi-core you will profit by executing on the ThreadPool.
Under Win-CE you are probably running on a single core, making part of this reasoning academic.

I don't think I'd use a Timer at all. A Timer is going to spawn a thread when it fires, which a) takes more time and b) allows for reentrancy, meaning you could be running your methods, especially if they take a while, simultaneously.
I'd spawn a single thread at startup (you define what that means - app startup, some object creation, etc) that does all the reads sequentially, does a Sleep call and then repeats.
Something along these lines:
private void Startup()
{
new Thread(WorkerProc) { IsBackground = true }
.Start();
}
private void WorkerProc()
{
int pollPeriod = 50;
while (true)
{
var et = Environment.TickCount;
// call your methods
et = Environment.TickCount - et;
var sleep = pollPeriod - et;
if (sleep < 0) sleep = 0; // always yield
Thread.Sleep(sleep);
}
}

It boils down to how accurate those methods needs to be. Calling each method in sequence (using the same timer) will not run all methods every 50ms, since each method takes time to complete.
If all methods must run every 50s: use different timers; otherwise use the same timer.

as it looks you dont depend on the order of your operations, otherwise you wouldnt ask the question.
I would prefer the "1 Timer per operation" solution. If you have an operation which is once more time consuming (lot of data whatever) at least the other operations will still get executed. But I dont know if that really helps you. It depends a lot about your needs/implementation

I would go for Solution 1, at least for your CPU intensive methods.
Then you implicitly run your methods in sequence. I assume that since your are on WinCE you don't have that many cores or that much RAM and the best trade of is to not try to run more code in parallel than necessary.
In Solution 2 you run into the risk of creating multiple thread executing your 10 methods at the same time. This might be good if you are waiting on I/O, especially network I/O.

Related

Odd behavior when trying to delay loop with Thread.Sleep(Timespan) [duplicate]

I want to call thread sleep with less than 1 millisecond.
I read that neither thread.Sleep nor Windows-OS support that.
What's the solution for that?
For all those who wonder why I need this:
I'm doing a stress test, and want to know how many messages my module can handle per second.
So my code is:
// Set the relative part of Second hat will be allocated for each message
//For example: 5 messages - every message will get 200 miliseconds
var quantum = 1000 / numOfMessages;
for (var i = 0; i < numOfMessages; i++)
{
_bus.Publish(new MyMessage());
if (rate != 0)
Thread.Sleep(quantum);
}
I'll be glad to get your opinion on that.
You can't do this. A single sleep call will typically block for far longer than a millisecond (it's OS and system dependent, but in my experience, Thread.Sleep(1) tends to block for somewhere between 12-15ms).
Windows, in general, is not designed as a real-time operating system. This type of control is typically impossible to achieve on normal (desktop/server) versions of Windows.
The closest you can get is typically to spin and eat CPU cycles until you've achieved the wait time you want (measured with a high performance counter). This, however, is pretty awful - you'll eat up an entire CPU, and even then, you'll likely get preempted by the OS at times and effectively "sleep" for longer than 1ms...
The code below will most definitely offer a more precise way of blocking, rather than calling Thread.Sleep(x); (although this method will block the thread, not put it to sleep). Below we are using the StopWatch class to measure how long we need to keep looping and block the calling thread.
using System.Diagnostics;
private static void NOP(double durationSeconds)
{
var durationTicks = Math.Round(durationSeconds * Stopwatch.Frequency);
var sw = Stopwatch.StartNew();
while (sw.ElapsedTicks < durationTicks)
{
}
}
Example usage,
private static void Main()
{
NOP(5); // Wait 5 seconds.
Console.WriteLine("Hello World!");
Console.ReadLine();
}
Why?
Usually there are a very limited number of CPUs and cores on one machine - you get just a small number if independent execution units.
From the other hands there are a number of processes and many more threads. Each thread requires some processor time, that is assigned internally by Windows core processes. Usually Windows blocks all threads and gives a certain amount of CPU core time to particular threads, then it switches the context to other threads.
When you call Thread.Sleep no matter how small you kill the whole time span Windows gave to the thread, as there is no reason to simply wait for it and the context is switched straight away. It can take a few ms when Windows gives your thread some CPU next time.
What to use?
Alternatively, you can spin your CPU, spinning is not a terrible thing to do and can be very useful. It is for example used in System.Collections.Concurrent namespace a lot with non-blocking collections, e.g.:
SpinWait sw = new SpinWait();
sw.SpinOnce();
Most of the legitimate reasons for using Thread.Sleep(1) or Thread.Sleep(0) involve fairly advanced thread synchronization techniques. Like Reed said, you will not get the desired resolution using conventional techniques. I do not know for sure what it is you are trying to accomplish, but I think I can assume that you want to cause an action to occur at 1 millisecond intervals. If that is the case then take a look at multimedia timers. They can provide resolution down to 1ms. Unfortunately, there is no API built into the .NET Framework (that I am aware of) that taps into this Windows feature. But you can use the interop layer to call directly into the Win32 APIs. There are even examples of doing this in C# out there.
In the good old days, you would use the "QueryPerformanceTimer" API of Win32, when sub milisecond resolution was needed.
There seems to be more info on the subject over on Code-Project: http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx
This won't allow you to "Sleep()" with the same resolution as pointed out by Reed Copsey.
Edit:
As pointed out by Reed Copsey and Brian Gideon the QueryPerfomanceTimer has been replaced by Stopwatch in .NET
I was looking for the same thing as the OP, and managed to find an answer that works for me. I'm surprised that none of the other answers mentioned this.
When you call Thread.Sleep(), you can use one of two overloads: An int with the number of milliseconds, or a TimeSpan.
A TimeSpan's Constructor, in turn, has a number of overloads. One of them is a single long denoting the number of ticks the TimeSpan represents. One tick is a lot less than 1ms. In fact, another part of TimeSpan's docs gave an example of 10000 ticks happening in 1ms.
Therefore, I think the closest answer to the question is that if you want Thread.Sleep for less than 1ms, you would create a TimeSpan with less than 1ms worth of ticks, then pass that to Thread.Sleep().

Task.Delay(<ms>).Wait(); sometimes causing a 15ms delay in messaging system [duplicate]

I want to call thread sleep with less than 1 millisecond.
I read that neither thread.Sleep nor Windows-OS support that.
What's the solution for that?
For all those who wonder why I need this:
I'm doing a stress test, and want to know how many messages my module can handle per second.
So my code is:
// Set the relative part of Second hat will be allocated for each message
//For example: 5 messages - every message will get 200 miliseconds
var quantum = 1000 / numOfMessages;
for (var i = 0; i < numOfMessages; i++)
{
_bus.Publish(new MyMessage());
if (rate != 0)
Thread.Sleep(quantum);
}
I'll be glad to get your opinion on that.
You can't do this. A single sleep call will typically block for far longer than a millisecond (it's OS and system dependent, but in my experience, Thread.Sleep(1) tends to block for somewhere between 12-15ms).
Windows, in general, is not designed as a real-time operating system. This type of control is typically impossible to achieve on normal (desktop/server) versions of Windows.
The closest you can get is typically to spin and eat CPU cycles until you've achieved the wait time you want (measured with a high performance counter). This, however, is pretty awful - you'll eat up an entire CPU, and even then, you'll likely get preempted by the OS at times and effectively "sleep" for longer than 1ms...
The code below will most definitely offer a more precise way of blocking, rather than calling Thread.Sleep(x); (although this method will block the thread, not put it to sleep). Below we are using the StopWatch class to measure how long we need to keep looping and block the calling thread.
using System.Diagnostics;
private static void NOP(double durationSeconds)
{
var durationTicks = Math.Round(durationSeconds * Stopwatch.Frequency);
var sw = Stopwatch.StartNew();
while (sw.ElapsedTicks < durationTicks)
{
}
}
Example usage,
private static void Main()
{
NOP(5); // Wait 5 seconds.
Console.WriteLine("Hello World!");
Console.ReadLine();
}
Why?
Usually there are a very limited number of CPUs and cores on one machine - you get just a small number if independent execution units.
From the other hands there are a number of processes and many more threads. Each thread requires some processor time, that is assigned internally by Windows core processes. Usually Windows blocks all threads and gives a certain amount of CPU core time to particular threads, then it switches the context to other threads.
When you call Thread.Sleep no matter how small you kill the whole time span Windows gave to the thread, as there is no reason to simply wait for it and the context is switched straight away. It can take a few ms when Windows gives your thread some CPU next time.
What to use?
Alternatively, you can spin your CPU, spinning is not a terrible thing to do and can be very useful. It is for example used in System.Collections.Concurrent namespace a lot with non-blocking collections, e.g.:
SpinWait sw = new SpinWait();
sw.SpinOnce();
Most of the legitimate reasons for using Thread.Sleep(1) or Thread.Sleep(0) involve fairly advanced thread synchronization techniques. Like Reed said, you will not get the desired resolution using conventional techniques. I do not know for sure what it is you are trying to accomplish, but I think I can assume that you want to cause an action to occur at 1 millisecond intervals. If that is the case then take a look at multimedia timers. They can provide resolution down to 1ms. Unfortunately, there is no API built into the .NET Framework (that I am aware of) that taps into this Windows feature. But you can use the interop layer to call directly into the Win32 APIs. There are even examples of doing this in C# out there.
In the good old days, you would use the "QueryPerformanceTimer" API of Win32, when sub milisecond resolution was needed.
There seems to be more info on the subject over on Code-Project: http://www.codeproject.com/KB/cs/highperformancetimercshar.aspx
This won't allow you to "Sleep()" with the same resolution as pointed out by Reed Copsey.
Edit:
As pointed out by Reed Copsey and Brian Gideon the QueryPerfomanceTimer has been replaced by Stopwatch in .NET
I was looking for the same thing as the OP, and managed to find an answer that works for me. I'm surprised that none of the other answers mentioned this.
When you call Thread.Sleep(), you can use one of two overloads: An int with the number of milliseconds, or a TimeSpan.
A TimeSpan's Constructor, in turn, has a number of overloads. One of them is a single long denoting the number of ticks the TimeSpan represents. One tick is a lot less than 1ms. In fact, another part of TimeSpan's docs gave an example of 10000 ticks happening in 1ms.
Therefore, I think the closest answer to the question is that if you want Thread.Sleep for less than 1ms, you would create a TimeSpan with less than 1ms worth of ticks, then pass that to Thread.Sleep().

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

Windows Service how to slow down infinite loop

The way I was told to make windows services is as followed:
Thread serviceThread = new Thread(new Thread(runProc())
Boolean isRunning = true;
if (_isRunning)
{
serviceThread.Start();
}else
close and log service
void runProc()
{
while(_isRunning)
{
//Service tasks
}
_isRunning = false;
}
This has worked fine for me so far but now I need to make a service that has big breaks in it, up to 2 hours at a time. Also I have started using timers so nothing is being done in the infinite loop other than stopping runProc() running over and over again which I can imagine is bad because threads are being made and remade a lot.
My question is, I have read that it is bad practice to put Thread.Sleep(big number) in that while(_isRunning) infinite loop, is this true? If this is the case, how do I get around the loop running constantly and using loads of resource? There is literally nothing being done in the loop right now, it is all handled in the tickevent of my timer, the only reason I have a loop is to stop runProc ending.
Thanks a lot an sorry if I explain myself badly
Thread.Sleep is bad because it cannot be (easily) interrupted1.
I generally prefer to use a ManualResetEvent or similar:
class abc {
Thread serviceThread = new Thread(new Thread(runProc())
ManualResetEvent abort = new ManualResetEvent(false);
void Start(){
serviceThread.Start();
}
void Stop(){
abort.Set();
serviceThread.Join();
}
void runProc()
{
while(!abort.WaitOne(delay))
{
//Service tasks
}
}
}
Hopefully you get the gist, not a great code sample.
The delay can be as large or small as you want (and can be arbitrarily recomputed during each loop). The WaitOne call will either delay the progress of this thread for delay milliseconds or, if Stop is called, will cause the loop to exit immediately.
1To summarize my position from the comments below - it can only be interrupted by blunt tools like Thread.Abort or Thread.Interrupt which both share the failing (to a greater or lesser extent) that they can also introduce their associated exceptions at various other places in your code. If you can guarantee that the thread is actually inside the Thread.Sleep call then the latter may be okay - but if you can make such a guarantee, you can also usually arrange to use a less blunt inter-thread communication mechanism - such as the one I've suggested in this answer.
I've always written services with a main infinite loop, not timers. Inside the loop, I check to see if there's any work to do, if so I do the work, if not I call Thread.Sleep(). That means that as long as there's work to be done, the loop will keep iterating, running as fast as it can. When the queue of work "dries up", it sleeps a little (a few seconds or minutes) while more work becomes available.
That's always worked really well for back-end jobs on a server where there's a constant stream of new work to be done throughout the day (and night). If you have big periods with no work the service will wake many times to check and then go back to sleep. You might like that or not. As long as the check is quick, it shouldn't be an issue. An alternative is to use a scheduled task (or database job) so that you know that work will be completed at specific times throughout the day. That's a better approach in some cases.

C# Improvement on a Fire-and-Forget

Greetings
I have a program that creates multiples instances of a class, runs the same long-running Update method on all instances and waits for completion. I'm following Kev's approach from this question of adding the Update to ThreadPool.QueueUserWorkItem.
In the main prog., I'm sleeping for a few minutes and checking a Boolean in the last child to see if done
while(!child[child.Length-1].isFinished) {
Thread.Sleep(...);
}
This solution is working the way I want, but is there a better way to do this? Both for the independent instances and checking if all work is done.
Thanks
UPDATE:
There doesn't need to be locking. The different instances each have a different web service url they request from, and do similar work on the response. They're all doing their own thing.
If you know the number of operations that will be performed, use a countdown and an event:
Activity[] activities = GetActivities();
int remaining = activities.Length;
using (ManualResetEvent finishedEvent = new ManualResetEvent(false))
{
foreach (Activity activity in activities)
{
ThreadPool.QueueUserWorkItem(s =>
{
activity.Run();
if (Interlocked.Decrement(ref remaining) == 0)
finishedEvent.Set();
});
}
finishedEvent.WaitOne();
}
Don't poll for completion. The .NET Framework (and the Windows OS in general) has a number of threading primitives specifically designed to prevent the need for spinlocks, and a polling loop with Sleep is really just a slow spinlock.
You can try Semaphore.
A blocking way of waiting is a bit more elegant than polling. See the Monitor.Wait/Monitor.Pulse (Semaphore works ok too) for a simple way to block and signal. C# has some syntactic sugar around the Monitor class in the form of the lock keyword.
This doesn't look good. There is almost never a valid reason to assume that when the last thread is completed that the other ones are done as well. Unless you somehow interlock the worker threads, which you should never do. It also makes little sense to Sleep(), waiting for a thread to complete. You might as well do the work that thread is doing.
If you've got multiple threads going, give them each a ManualResetEvent. You can wait on completion with WaitHandle.WaitAll(). Counting down a thread counter with the Interlocked class can work too. Or use a CountdownLatch.

Categories