simpler C# code to introduce 1 mSec delay? - c#

I am not using Thread so can't use thread.sleep() method.. Its part of my program where I need to introduce some delay .. Not precisely 1mSec but almost that ..
which is the standard method that is known to be so??

You are always using a thread. Every application has at least one thread, so Thread.Sleep will work fine.

I am not using Thread so can't use thread.sleep() method
Not sure you you say that -- you can use Thread.Sleep anywhere you like.

Just so you know, a 1msec sleep isn't guaranteed be exactly 1msec, in fact it's very improbable due to it being such a small time. The thread.sleep(x) states x as a minimum sleep time, if you wan't a much more exact sleep you might want to look into win32 multimedia timers: http://msdn.microsoft.com/en-us/library/dd742877.aspx

Don't sleep 1msec. It will not be accurate at all. Read for instance this article or this
Thread.sleep will always suspend the current thread. Keep in mind that it's not a good idea to use Sleep on a GUI thread (if your app is a winform app).

If you are just trying to provide an opportunity for thread switching, then use Thread.Sleep(0). (This is equivalent to Thread.Yield() in Java.)
Edit: actually seems like they've added Thread.Yield() in .NET 4.

Related

Thread.Sleep() usage to Prevent Server Overload

I wrote some code that mass imports a high volume of users into AD. To refrain from overloading the server, I put a thread.sleep() in the code, executed at every iteration.
Is this a good use of the method, or is there a better alternative (.NET 4.0 applies here)?
Does Thread.Sleep() even aid in performance? What is the cost and performance impact of sleeping a thread?
The Thread.Sleep() method will just put the thread in a pause state for the specified amount of time. I could tell you there are 3 different ways to achieve the same Sleep() calling the method from three different Types. They all have different features. Anyway most important, if you use Sleep() on the main UI thread, it will stop processing messages during that pause and the GUI will look locked. You need to use a BackgroundWorker to run the job you need to sleep.
My opinion is to use the Thread.Sleep() method and just follow my previous advice. In your specific case I guess you'll have no issues. If you put some efforts looking for the same exact topic on SO, I'm sure you'll find much better explanations about what I just summarized before.
If you have no way to receive a feedback from the called service, like it would happen on a typical event driven system (talking in abstract..we could also say callback or any information to understand how the service is affected by your call), the Sleep may be the way to go.
I think that Thread.Sleep is one way to handle this; #cHao is correct that using a timer would allow you to do this in another fashion. Essentially, you're trying to cut down number of commands sent to the AD server over a period of time.
In using timers, you're going to need to devise a way to detect trouble (that's more intuitive than a try/catch). For instance, if your server starts stalling and responding slower, you're going to continue stacking commands that the server can't handle (which may cascade in other errors).
When working with AD I've seen the Domain Controller freak out when too many commands come in (similar to a DOS attack) and bring the server to a crawl or crash. I think by using the sleep method you're creating a manageable and measurable flow.
In this instance, using a thread with a low priority may slow it down, but not to any controllable level. The thread priority will only be a factor on the machine sending the commands, not to the server having to process them.
Hope this helps; cheers!
If what you want is not overload the server you can just reduce the priority of the thread.
Thread.Sleep() do not consume any resources. However, the correct way to do this is set the priority of thread to a value below than Normal: Thread.Current.Priority = ThreadPriority.Lowest for example.
Thread.Sleep is not that "evil, do not do it ever", but maybe (just maybe) the fact that you need to use it reflects some lack on solution design. But this is not a rule at all.
Personally I never find a situation where I have to use Thread.Sleep.
Right now I'm working on an ASP.NET MVC application that uses a background thread to load a lot of data from database into a memory cache and after that write some data to the database.
The only feature I have used to prevent this thread to eat all my webserver and db processors was reduce the thread priority to the Lowest level. That thread will get about to 35 minutes to conclude all the operations instead of 7 minutes if a use a Normal priority thread. By the end of process, thread will have done about 230k selects to the database server, but this do not has affected my database or webserver performance in a perceptive way for the user.
tip: remember to set the priority back to Normal if you are using a thread from ThreadPool.
Here you can read about Thread.Priority:
http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx
Here a good article about why not use Thread.Sleep in production environment:
http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx
EDIT Like others said here, maybe just reduce your thread priority will not prevent the thread to send a large number of commands/data to AD. Maybe you'll get better results if you rethink all the thing and use timers or something like that. I personally think that reduce priority could resolve your problem, although I think you need to do some tests using your data to see what happens to your server and other servers involved in the process.
You could schedule the thread at BelowNormal priority instead. That said, that could potentially lead to your task never running if something else overloads the server. (Assuming Windows scheduling works the way the documentation on scheduling threads mentions for "some operating systems".)
That said, you said you're moving data into AD. If it's over the nework, it's entirely possible the CPU impact of your code will be negligible compared to I/O and processing on the AD side.
I don't see any issue with it except that during the time you put the thread to sleep then that thread will not be responsive. If that is your main thread then your GUI will become non responsive. If it is a background thread then you won't be able to communicate with it (eg to cancel it). If the time you sleep is short then it shouldn't matter.
I don't think reducing the priority of the thread will help as 1) your code might not even be running on the server and 2) most of the work being done by the server is probably not going to be on your thread anyway.
Thread.sleep does not aid performance (unless your thread has to wait for some resource). It incurs at least some overhead, and the amount of time that you sleep for is not guaranteed. The OS can decide to have your Thread sleep longer than the amount of time you specify.
As such, it would make more sense to do a significant batch of work between calls to Thread.Sleep().
Thread.Sleep() is a CPU-less wait state. Its overhead should be pretty minimal. If execute Thread.Sleep(0), you don't [necessarily] sleep, but you voluntarily surrender your time slice so the scheduler can let lower priority thread run.
You can also lower your thread's priority by setting Thread.Priority.
Another way of throttling your task is to use a Timer:
// instantiate a timer that 'ticks' 10 times per second (your ideal rate might be different)
Timer timer = new Timer( ImportUserIntoActiveDirectory , null , 0 , 100 ) ;
where ImportUserIntoActiveDirectory is an event handler that will import just user into AD:
private void ImportUserIntoActiveDirectory( object state )
{
// import just one user into AD
return
}
This lets you dial things in. The event handler is called on thread pool worker threads, so you don't tie up your primary thread. Let the OS do the work for you: all you do is decide on your target transaction rate.

System.Threading Sleep function help? (C#)

I'm new in C# and I'm using System.Threading.
I have this code:
UISystem.SetScene(Scene_Menu);
Thread.Sleep (9000);
p.Text="HELLO";
Thread.Sleep(9000);
p.Text="WORLD";
It delays 18 seconds, but the p.Text="HELLO" doesn't show between the sleep functions. What's the problem with my code?
Thanks.
Timers don't work since I can't edit p from a separate thread.
Application.DoEvents() is a Windows Forms function, I'm building an application in PS Vita.
You have discovered why you should never use Thread.Sleep. It is useful for only two things. (1) Writing test cases that need to simulate a thread being busy for a certain number of seconds, and (2) Sleeping for zero milliseconds tells the operating system "I cede the rest of my time slice to another process if there exists one that wants it"; it's a politeness thing.
You should never use thread.Sleep to introduce a delay as you are doing for exactly the reason you have discovered. You are setting a property, but setting a property does not cause the operating system to repaint the screen. Consider if it did; you might have a thousand property sets in a method, and you would have to repaint the screen after all of them, which would look ugly and be very slow.
Instead what happens is the property is set and the object makes a note to the operating system that says when this thread is available to handle operating system messages again, please repaint me. Your program is, instead of telling the operating system "I'm done, go ahead and see if there are any message for me" that instead you want the thread to do nothing for nine seconds.
Now, you can tell the program to check for messages by calling DoEvents but using DoEvents is also a bad idea and you should not do it. Doing so essentially causes your program to exhibit symptoms of Attention Deficit Disorder; you have not finished the current job and you are looking to see if there are new jobs to do without removing the old jobs from the call stack! Suppose those new jobs in turn get interrupted, and so on, and so on. The stack grows without bound, which is very bad. DoEvents is a "worst practice", just like sleeping a thread. You can get away with it in small simple programs but it leads to big trouble when the program becomes complex.
Moreover: yes, DoEvents will paint your control, but that is all it will do. For the next nine seconds, the application will appear to the user to be completely hung. That is a very bad user experience.
The right thing to do if you want to introduce a delay is to asynchronously wait. In C# 4 and earlier the standard way to do that is to create a timer, and when the timer ticks, do the next thing.
Now, you say that you cannot use a timer because you need to access the control from the UI thread. That's fine. The timer's tick event handler will run on the UI thread, not on a separate thread. You can safely use a timer.
In C# 5, the right thing to do is to use the new await keyword to introduce an asynchronous wait. That is, a wait that does other stuff while it is waiting, instead of going to sleep while it is waiting. In C# 5 you would write your code as:
UISystem.SetScene(Scene_Menu);
await Task.Delay (9000);
p.Text="HELLO";
await Task.Delay(9000);
p.Text="WORLD";
C# 5 is at present in beta; for details on this new feature see:
http://msdn.microsoft.com/en-us/async
For a gentle introduction to async and an explanation of why DoEvents is bad news, see my MSDN magazine article:
http://msdn.microsoft.com/en-us/magazine/hh456401.aspx

Thread.Sleep() sleeps for longer

I have a Winform which needs to wait for about 3 - 4 hours. I can't close and somehow reopen the App, as it does few things in background, while it waits.
To achieve the wait - without causing trouble to the UI thread and for other reasons -, I have a BackgroundWorker to which I send how many milliseconds to wait and Call Thread.Sleep(waitTime); in its doWork event. In the backGroundWorker_RunWorkerCompleted event, I do what the program is supposed to do after the wait.
This works fine on the development machine. i.e. the wait ends when it has to end. But on the Test machine, it keeps waiting for longer. It happened two times, first time it waited exactly 1 hour more than specified time and second time it waited more for about 2 Hours and 40 minutes.
Could there be any obvious reason for this to happen or am I missing something?
The dev machine is Win XP and Test machine is Win 7.
I propose to use ManualResetEvent instead:
http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(waitTime);
...
//your background worker process
mre.Set();
As a bonus you will have an ability to interrupt this sleep quicker.
Have a look at this article which explains the reason:
Thread.Sleep(n) means block the current thread for at least the number
of timeslices (or thread quantums) that can occur within n
milliseconds. The length of a timeslice is different on different
versions/types of Windows and different processors and generally
ranges from 15 to 30 milliseconds. This means the thread is almost
guaranteed to block for more than n milliseconds. The likelihood that
your thread will re-awaken exactly after n milliseconds is about as
impossible as impossible can be. So, Thread.Sleep is pointless for
timing.
By the way it also explains why not to use Thread.Sleep ;)
I agree to the other recommendations to use a Timer instead of the Thread.Sleep.
In my humble opinion, the difference in wait time cannot solely be explained by the information that you have given us. I would really think that the cause of the difference lies within the moment of starting the sleep. So the actual Thread.sleep(waitTime); call. Are you sure that the sleep is called at the moment you think it is?
And, as suggested by the comment, if you really need to wait for this long; consider using a Timer to start the events needed. Or even scheduling of some sort, within your application. Of course, this depends on your actual implementation and thus can be easier said than done. But it 'feels' silly, letting a BackgroundWorker sleep for so long.
PREFIX: This requires .NET 4 or newer
Consider making your function async and simply doing:
await Task.Delay(waitTime);
Alternately, if you can't make your function async (or don't want to) you could also do:
Task.Delay(waitTime).Wait();
This is a one-line solution and anyone with a copy of Reflector can verify that Task.Delay uses a timer internally.

Multi Thread Programming

I have a task. I have some random number, wich contains value of this number, and delay.
Delay means, that after this delay (in seconds) this number gonna be updated (value and delay).
And all I need to do is next: for example I have 5 numbers. All of them are on the same form. So when programm start, it must take first number, get its delay, do smth like Thread.Sleep(delay) for this number, update it, then get second number, get delay and so on. When it reach the last one, it must get first number again, then second and so on. Like loop.
I'm new in threads. So could someone explain me how should it work?
So I have main form, then I have 5 UserControls on it (I keep them in List<>). Each control have UpdateNumber() method, which update value and delay of current number. What should I do on main form? Do I need create Thread[] array? Then put each UserControl in there? Then start all of them and monitor them somehow?
I think it smth about Thread.Join. But for me, as for newbie it's pretty complicated.
P.S. and than I need to next task. It's the same, but all this numbers works separetly. For example first numbers has 5 second delay in the begining. When it reachs 5 second delay, it's update itself. Second number and all others do the same.
I would avoid creating threads and using Thread.Sleep(). Each thread is an expensive resource to create and since it will be asleep the majority of the time, it will be wasted the majority of the time. Also, when it executes it may cause context switching since the CPU's may be saturated.
Instead, I would consider using a System.Threading.Timer. For instance, you initially set the Timer to operate on the first value. After this operation is complete you use your 'delay' to set the Timer to execute the code that will read the next value using Timer.Change() and so on. I'm not sure I understand your requirements completely but it sounds like you should be able to satisfy most of them using a Timer. The Timer will use the ThreadPool which will avoid unnecessary thread creation and context switching.
To learn more about multi-threading I highly recommend Jeffrey Richter's book CLR via C# (part V). Multi-threading is very powerful but it is incredibly easy to get totally wrong. IMHO anyone who wants to write multi-threaded code should at least read a good text such as this before starting.
Based only on what I have read I do not see any compelling reason to use threads at all. I mean you are just generating different random numbers based on some time interval so it cannot possibly be that CPU intensive. Just use a System.Windows.Forms.Timer in each UserControl. When the Tick event handler is executed then just generate next number.
If you are asking if it is a good idea to run each UserControl in a different thread then the answer is most definitely no. All UI elements including Form's and Control's must run in the specially designated UI thread. This is mandatory. It will not work right correctly (or at all) on a free thread.
Regarding calling Thread.Join; do not attempt this, at least on a UI thread anyway. Calling Join on a UI thread will block the windows message dispatching mechanisms. It will appear as if the whole UI hung up.

What's the reason of using Thread.Sleep in multi-threaded applications?

Often times I when I see some multi-threaded code, I see Thread.Sleep() statements in the code.
I even had a crash where I was trying to figure out the problem, so commented out most of the multi-threaded code and slowly brought it and for the final piece when I added a for statement like:
for ( int i = 0; i < 1000000; ++i )
++i;
it didn't crash. So now I replaced it Thread.Sleep() and it seems to work. I can't repro it easily to post it here, but is using Thread.Sleep() necessary for multi-threaded applications?
What's the purpose of them? Would it lead to unexpected results if not used?
EDIT: Btw I am using the BackgroundWorker and only implementing my stuff in there, but not sure what causes this. Although I am using an API which is the hosting app where the app is not multi threaded. So for instance I think I can't call it's API functions on several threads at once. Not sure, but that was my guess.
Typically, Thread.Sleep is a sign of a bad design. That being said, its MUCH better than eating 100% of the CPU core time, which is what the for loop above is doing.
A better option is typically to use a WaitHandle, such as a ManualResetEvent, to trigger the continuation of the thread's execution when the "event" (which is the reason to delay) occurs. Alternatively, using a Timer can work as well in many cases.
The Thread.Sleep(1) allows switch to execution another thread. So if you have more threads than cores/processors and you know "now I did in this thread a lot of work and next work can be done little-bit later" you call Thread.Sleep(1) and allows another thread to do some work sooner than the native switcher will "pause" the currently executed thread.
Try this: Write a program that launches 100 threads, and put each of the thread into a for loop as you described. And then write another that launches 100 threads and uses Thread.Sleep instead.
Run them both and compare the CPU usage. You'll see the point. =)
Thread.Sleep() simply causes the executing thread to halt for the specified duration.
I've seen many developers use Thread.Sleep() because they don't probably handle the joining of dependent threads. They simply use Thread.Sleep() to force a thread to wait for some amount of time until the think their other threads would have finished and have their data available.
If you have two threads that need to wait on each other to proceed with their processing, you should really use the mechanisms built in to .NET that are meant to handle situations like that (ie. ManualResetEvent, etc.)
Thread.Sleep() is OK to use in some situations eg. watchdog threads.
However in your case, it may not seem to be the optimal solution as pointed out by others.
Without a code sample, it's hard to tell, but based on your description, I don't think it's a question of Thread.Sleep() or not. I would suspect that you may be suffering from a race condition - that's usually why you experience "random" buggy behavior or even "random" crashes in multithreaded code - as seems to be what you are experiencing.
For whatever reason, your for-loop may cause the subtle critical timings of the race condition to occur less often, but it won't solve the root cause. There are many pitfalls to be aware of when doing multithreaded programming, I can only advice you to read up on the topic if you want to be able to avoid these.
I'll recommend reading http://www.amazon.com/Concurrent-Programming-Windows-Joe-Duffy/dp/032143482X

Categories