So Thread.Sleep() is bad (http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx).
Is there any recommended alternative to simulating a pause in execution of a program? Eg a loop? Although I suppose this involves a lot of overhead in initialising variables, checking the bool condition, etc.
Thanks
If you are only going to simulate a pause (as in for test purposes), I think Thread.Sleep is a perfectly valid approach. On the other hand, if you are actually waiting for something, some sort of thread-safe signalling mechanism would be better (check the types that inherits WaitHandle).
simulating a pause
"Simulating" sounds like something you would only do in debugging. Thread.Sleep should be fine.
The main problem with Sleep is that usually you should be waiting for something specific to occur rather than waiting for an arbitrary delay.
The other thing to watch out for is calling Thread.Sleep from a UI thread, which will make the UI unresponsive. Better to disable the parts of the UI that you do not want the user to interact with and then use a Timer control to implement the delay.
From what you said, you're trying to simulate a pause in execution.
Thread.Sleep is perfectly valid for that. Even the article you linked starts with:
Thread.Sleep has it's use: simulating lengthy operations while testing/debugging on an MTA thread.
I don't agree with the assessment that Thread.Sleep() is "bad". It depends on the situation.
In a console mode program, it might be perfectly appropriate to sleep the thread if you're waiting for something. Perhaps even in a loop: Check the condition, sleep for a bit if it's not satisfied, repeat.
In a graphical program however, normally you would not sleep on the main (GUI) thread. This is because these days GUI interfaces are designed with a single interactive thread. If you sleep on that thread, your whole GUI will appear to "lock up" for the time that you're sleeping. A better situation might be to use some kind of timer (all GUI frameworks have such a concept).
One thing you do not want to do is write a loop that continually checks for some condition to be true, without even sleeping. This will cause one CPU to run up to 100% because the CPU wants to get its work done as fast as possible. Not only is this unexpected from a user point of view, but it's unfriendly because such activity can starve the process that you're actually waiting for of enough cycles to get its work done!
If you're waiting for some code or event to occur, you can use wait handles.
While the article itself is debatable, I agree with its starting sentence, which addresses your concern
Thread.Sleep has it's use: simulating
lengthy operations while
testing/debugging on an MTA thread.
In .NET there's no other reason to use
it.
I believe that's what you are asking about (simulating pauses) and is the main use of Thread.Sleep()
I use the System.Timers:
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
I believe Raymond Chen has recommended to set the thread priority lower
http://blogs.msdn.com/oldnewthing/archive/2009/07/27/9849503.aspx
I don't quite understand why you want to pause every so often. Why not just do the work at low priority? When there are more important things to do, your background thread will stop doing whatever it's doing. When there is an available CPU, then your background thread will do its thing as fast as it can (until something with higher priority arrives).
I would be willing to bet that in the majority of cases where a programmer thinks of using Thread.Sleep(), some simple code that uses events would work very well.
Related
I was trying to use AutoResetEvent.WaitOne() on a GUI thread hoping that it would not block the GUI thread completely and allow the GUI thread to keep pumping windows messages while it waits for a signal (similar to Thread.Wait()). I learned that wasn't a correct assumption.
So am looking for a way to be on the GUI Thread and wait for a thread to finish running (similar to using AutoResetEvent.WaitOne()) but keep the message pump flowing. (Please no DoEvents())
I guess the short question is: Is there a WAIT in .NET that pumps windows messages (especially "Paint" event) while it is waiting?
The CLR has a special workaround for calling WaitOne() on an STA thread. That is illegal, a thread that supports apartment threading is not allowed to block. That's very prone to cause deadlock. The CLR will in fact start taking over the duty of pumping messages, roughly similar to MsgWaitForMultipleObjects. Very roughly.
While this works to keep the basic plumbing of a UI thread alive, like painting, this is not ever something you want to do if you can avoid it. Quirky stuff can happen, not quite unlike using Application.DoEvents(), although the CLR code does try to minimize the damage that the re-entrancy can cause.
Big secret how they do this btw, it was intentionally omitted from the SSCLI20 distribution which is otherwise a very complete copy of the CLR code. Chris Brumme blogged about it, pretty impenetrable in his usual way, but with just waving his hands and not giving away any good secrets. The code itself is quite resistant to reverse engineering, it is large. The only common signs of it is finding it back in a stack trace from a programmer that's got a very hard problem to solve.
In other words, you are invoking a code path that's highly undocumented and poorly understood. Don't do it. It is fundamentally unnecessary, you can always invoke back to the UI thread and continue with the code that you've now got after the WaitOne() call. That's safe.
I don't know of any such thing that you're asking for. AFIK (as far as i know), you'll need to start a second background task or thread which waits for the AutoResetEvent to trigger in the background thread and in your UI thread, once you launch the task or 2nd thread, exit your method so it is free to do it's job of 'message pumping' as you put it.
So in this scenario, the background thread would then need to finish your processing once its AutoResetEvent is triggered to continue the processing.
I have a software in C# I'm writing and every time its doing a hard task and I switch windows to let it complete the window screws up. Not sure how to word it but all of the buttons disappear or become "holes" . I know the application is running because the progress bar shows up again after a while. How do I fix this? I've been searching and I'm sure it has something to do with doubleBuffering.
you normally solve this by executing your resource intensive process in a separated thread than the main UI thread, in this way the UI thread can refresh the UI as needed and your long lasting operation is completed in parallel. After the background / worker thread has completed its task the control flow will return to the application.
Things are a bit more complicated when you want to update the status bar in the UI thread from the worked thread, usually you have to use the Invoke methods because you definitely should not even try to access and modify UI controls from another thread.
a bit cheaper method which kind of works but can have some issues from time to time is to include in your long lasting operation a call to Application.DoEvents() from time to time, for example if you are in a loop, every few iterations of the loop (depends on how much time it takes to execute a single iteration and on how many iterations you have in total); this method works and saves you completely from start working with multiple threads but is also considered less reliable.
As LarsTech already pointed out, use the BackgroundWorker-Class, especially for tasks which take longer than just a few seconds.
Make sure to use ReportProgress in your Backgroundworker to notify your Progressbar.
Good links worth studying:
http://www.albahari.com/threading/part3.aspx
http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners
What is the effect of calling Thread.CurrentThread.Join(), and if/when would it make sense to call it?
Was it really
CurrentThread.Join()
that you saw in real code - which I kind of doubt, unless it's some hack to prevent other threads to join on the current thread - or was it
CurrentThread.Join(someTimeout)
The latter is equivalent to
Thread.Sleep(someTimeout)
except that joining on the current thread allows message pumping to continue if you are in a GUI / COM situation.
What is the effect of calling Thread.CurrentThread.Join()
You will block the execution of the current thread, and effectively dead lock it. It will cause the current thread to block until the current thread finishes, which will never happen.
, and if/when would it make sense to call it?
It really doesn't make sense to do this. You should never call this method in this manner.
On a side note, since you're using .NET 4, I would recommend avoiding using Thread.Join in general. Using the new Task/Task<T> classes is far nicer in many ways, as you can easily attach continuations (or always call Task.Wait() if you truly need to block).
It actually make sense in world of observable. Lets say you have a queue listener in main and you want to keep main thread running forever.
Instead of doing while(true) and put your code in the loop, last line you can write this. This way current thread will also be parent thread for other threads spawned within the application.
Think of it as entry point for app.
No, CurrentThread.Join() makes no sense
This could make your program stop running, making the thread A wait for thread A for example.
If you are making a unit test that tests if timers perform well in lets say a Windows Service and you use Thread.Sleep() statements with more as 60 seconds in it you can get ContextSwitch errors because the Thread.Sleep() is blocking the message pump.
If you are replacing those Thread.Sleep() statements in your unit test with Thread.CurrentThread.Join() then those ContextSwitch error will go away. So its a non blocking solution.
You could say Thread.CurrentThread.Join() is a better Thread.Sleep().
CurrentThread.Join() can be used to put the current thread to sleep until another thread interrupts it.
For example, you may have a server where the main method sets up a pool of other threads to handle incoming requests, passes a reference to it's current thread to a shutdown-trap, and then goes to sleep until it's time for the server to shut down.
This is not a terribly common pattern but it would be wrong to say that there is no case where you'd want your current thread to sleep until interrupted.
In my C# project I have a form that is displayed which shows a progress bar.
Some processing is then done which involves communication over the internet.
While this processing is occurring the form says "Not Responding" when run in Win 7, in XP the form just goes white.
Either way, it is not acceptable.
Do I need to use threads to solve this problem?
What are some of the basics of threads that I would need to use in this scenario?
Your processing must be done within a thread.
Out of your thread you have to invoke your progress bar to show the progress.
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Value = (int)((i / limit) * 100);
});
Yes you have to use threads to keep your UI responsive while something gets done in background. But this question cannot be just answered just like "use Threads to solve it", because there are a lot of forms in which you could use threads. (Backgroundworker, Threadpool, Asynch IO, Creating a Thread, Task Parallel Library, CCR, and a lot more you could imagine for every kind of parallelization scenarios).
As you said you are doing some processing which needs connecting to internet. Where does the most amount of time spent? is it IO over network which takes most time in that case probably Asynchronous IO makes a lot of sense. If time spent is in one huge processing operation then Background worker is perfect, but if this processing can be further broken down into smaller chunks of parallel processing tasks then TPL or ThreadPool is preferred. Till now I am talking only about some processing which happens on Windows forms event, and keep the UI responsive. But based on the scenario there are numerous other options you could use to make threading work for you.
Asynch IO doesnt look like you are doing threading but it more matches with eventing model of winforms. So you could look at that if you are very comfortable with event based programming.
Threadpool looks more like a queue of workers to which you could keep throwing all the work needs to be done, and the framework figures out how many threads to run based on the kind of machine you are using (dual core, quad core etc) and it would get your work items doen in optimal way.
Bottom line its not one answer to use one over other, instead based on the kind of problem you are solving threading model needs to be decided on.
A cheaper option is to add the line Application.DoEvents() inside whatever loops your app is running, which will cause it to process messages each time it gets there.
If you use System.Net.WebClient, you can use DownloadDataAsync() to communicate in a non blocking way.
The System.Net.Sockets.Socket class proviede non blocking communication, too.
Sockets example
WebClient example
Yes, better way is use BackGroundWorker component. It is wrapper over threads, so you don't need to manage threads. You can get more info from Background worker on MSDN
As long as the program remain in the function to process something, the UI will not update. That is why you may need to start a background thread, so that your UI can continue functioning while your background thread can do the work. An alternatively is to use asynchronous functions.
example of background thread
From your description I'll assume that all your work is currently being done on a single thread, the main thread which is also used for your GUI.
The progress bar can only update when that main thread gets a chance to check its state and apply any expected changes.
Therefore it is important that your processing work does not occupy the main thread for extended periods of time.
There are two main approaches to handling this:
Stepping the processing activity.
Break down the processing step into a number of serial tasks - each short in nature.
Progressively call each of these serial tasks in the OnIdle event on your main thread.
Using a background thread.
See other answers giving more detail on how this would work.
The stepping approach can be useful if you want to avoid the sublties of thread synchronisation. The threading approach is probably better but only essential if it is impossible to guarantee serial short steps.
Scenario
I have a Windows Forms Application. Inside the main form there is a loop that iterates around 3000 times, Creating a new instance of a class on a new thread to perform some calculations. Bearing in mind that this setup uses a Thread Pool, the UI does stay responsive when there are only around 100 iterations of this loop (100 Assets to process). But as soon as this number begins to increase heavily, the UI locks up into eggtimer mode and the thus the log that is writing out to the listbox on the form becomes unreadable.
Question
Am I right in thinking that the best way around this is to use a Background Worker?
And is the UI locking up because even though I'm using lots of different threads (for speed), the UI itself is not on its own separate thread?
Suggested Implementations greatly appreciated.
EDIT!!
So lets say that instead of just firing off and queuing up 3000 assets to process, I decide to do them in batches of 100. How would I go about doing this efficiently? I made an attempt earlier at adding "Thread.Sleep(5000);" after every batch of 100 were fired off, but the whole thing seemed to crap out....
If you are creating 3000 separate threads, you are pushing a documented limitation of the ThreadPool class:
If an application is subject to bursts
of activity in which large numbers of
thread pool tasks are queued, use the
SetMinThreads method to increase the
minimum number of idle threads.
Otherwise, the built-in delay in
creating new idle threads could cause
a bottleneck.
See that MSDN topic for suggestions to configure the thread pool for your situation.
If your work is CPU intensive, having that many separate threads will cause more overhead than it's worth. However, if it's very IO intensive, having a large number of threads may help things somewhat.
.NET 4 introduces outstanding support for parallel programming. If that is an option for you, I suggest you have a look at that.
More threads does not equal top speed. In fact too many threads equals less speed. If your task is simply CPU related you should only be using as many threads as you have cores otherwise you're wasting resources.
With 3,000 iterations and your form thread attempting to create a thread each time what's probably happening is you are maxing out the thread pool and the form is hanging because it needs to wait for a prior thread to complete before it can allocate a new one.
Apparently ThreadPool doesn't work this way. I have never checked it with threads before so I am not sure. Another possibility is that the tasks begin flooding the UI thread with invocations at which point it will give up on the GUI.
It's difficult to tell without seeing code - but, based on what you're describing, there is one suspect.
You mentioned that you have this running on the ThreadPool now. Switching to a BackgroundWorker won't change anything, dramatically, since it also uses the ThreadPool to execute. (BackgroundWorker just simplifies the invoke calls...)
That being said, I suspect the problem is your notifications back to the UI thread for your ListBox. If you're invoking too frequently, your UI may become unresponsive while it tries to "catch up". This can happen if you're feeding too much status info back to the UI thread via Control.Invoke.
Otherwise, make sure that ALL of your work is being done on the ThreadPool, and you're not blocking on the UI thread, and it should work.
If every thread logs something to your ui, every written log line must invoke the main thread. Better to cache the log-output and update the gui only every 100 iterations or something like that.
Since I haven't seen your code so this is just a lot of conjecture with some highly hopefully educated guessing.
All a threadpool does is queue up your requests and then fire new threads off as others complete their work. Now 3000 threads doesn't sounds like a lot but if there's a ton of processing going on you could be destroying your CPU.
I'm not convinced a background worker would help out since you will end up re-creating a manager to handle all the pooling the threadpool gives you. I think more you issue is you've got too much data chunking going on. I think a good place to start would be to throttle the amount of threads you start and maintain. The threadpool manager easily allows you to do this. Find a balance that allows you to process data while still keeping the UI responsive.