Thread.Sleep() stealing debuggers focus - c#

Currently I have a background thread that does some periodic heavy data management. Because it only needs to run its process every few hundred milliseconds I call Thread.Sleep() at the end of the process and it then goes back to the top of the loop and repeats.
This is all working perfectly and doesn't cause any grief or performance issues for the rest of the software. The only thing that does bug me though is that when I break the debugger instead of going to my main threads current location, it gets stolen by the Thread.Sleep() and takes me there instead.
Is there any way that I can disable the debugger from stopping on that line, or is there an alternative to putting the Thread to sleep?
Thanks in advance!

One thing you could try is to put the Thread.Sleep() in a method and add the DebuggerStepThrough on it.
You can also just "freeze" the you don't want to "steal focus" from Threads window (Debug -> Windows -> Threads). Also remember to unfreeze them when you're done
As an aside using a Timer (there are two) or a AutoReset Event is preferred to using Thread.Sleep() See Is Sleep() evil?

Related

How Can I Make Designer-Made Form Events Yield to Other Threads?

How do I make GUI events yield to a given thread? By GUI events I mean things like opening a sub-form, selecting different tabs, or minimizing/maximizing my form or changing focus.
When my working thread gets data, can I throttle resources over to it, and deny those resources from other processes or threads in my application?
History:
In my question Here I explain a scenario where I am concerned with my Invoke to my main form causing hang-ups on my critical threads. It was then revealed to me that I have the option to "BeginInvoke".
Now I find that while BeginInvoke gets me half-way there, I'm still unable to avoid hang-ups in my critical threads. When I say "critical threads" I am refering to a thread that takes approximately 60ms to cycle, but must finish cycling before 130ms has elapsed. It sits there looping, polling a data list. When the data shows up, it generally takes between 40 and 60ms to finish processing.
I had (and technically, I plan to reinstate) a second thread throwing BeginInvokes at my form to update the user on the status of the run. I currently, for debugging purposes, am not doing that.
I did some profiling, and I noticed that I almost always keep my process time down far below 100ms, which I need to be, because my application needs to output results no later than when the next package of data appears (every 100ms, but for this example I slowed that to 130ms). When I interact with my form, by say changing focus, or minimizing/maximizing it, I can see my process time spike above 1s. I assume this is because silly things like minimizing or maximizing, or other re-draw events, are plundering all my precious clock time.
Platform:
I am using Visual C# 2008 with WinForms. The target machine runs Windows XP. I have attempted closing Windows Explorer, and running my application on Normal, High, and Realtime, priority, but I still see a nearly identical impact when manipulating my form.
Edit
I have tried to use Thread.CurrentThread.Priority to throttle my priority at critical times during my worker loop. This somehow isn't able to take those resources away from my GUI and operations that involve redrawing the GUI still rule over my poor worker thread.
Did you try and set the Thread Priority of your worker class to RealTime using the Thread.Priority property?
Based on the description of Scheduling Priorities this should give a higher priority to your worker thread. However, this will cause your GUI to stutter along, so you probably only want to set the priority high during critical time periods.

C# how should I go about creating this threading application?

Alright I will attempt to explain every aspect of why I need to do this a certain way. Basically, I need an application to execute a certain .exe multiple times asynchronously.
Specs:
I need to be able to restrict the amount of executions going at one time.
It has to use threading because my program has a GUI and simply launching the .exe's and monitoring them will lock up the .GUI AND the console for other things.
How should I go about doing this? (examples help me a lot)
I've already told you multiple times how you should go about this. The launcher program has a single thread. It monitors the child processes. If a process ends and there is a free processor, it starts up a new process and affinitizes the process to that processor. When it's not doing any of those things it yields control back to its UI. Since each of those operations is of short duration, the UI never appears to block.
UPDATE
Actually this wasn't a great answer. As Henk pointed out in my comments, when you call Process.Start() that's not a blocking call. You have to explicitly set Process.EnableRaisingEvents to true, and handle the Exited event. I'm not sure if the Exited event is fired in the calling thread (I doubt it, but you should check), but the point is starting a process isn't a blocking call, so you don't need more threads doing the waiting.
See this similar answer for more details: Async process start and wait for it to finish
PREVIOUS ANSWER
Fire off your threads (limited to your max number of threads), and have them run the external exe using the Process.Start() method. Make sure you set them to wait for the process to finish. When the processes finish, have the threads use something like Interlocked.Increment() to increment a counter variable that you can read from your main form code. Better still, have those threads call a callback delegate (e.g. Action<T>), which will in turn check for this.InvokeRequired before doing the actual work.

Monitoring C# Threads - Which does what/when

As everybody, I am used to debugging my code in VS in step-by-step mode. Well, now that I have an application with many Background Workers everywhere, I am not in Kansas anymore.
What is the most efficient way to debug threaded applications and be able to monitor each and every thread to keep track of what's happening all over the code?
As of now, I stick to good ol' debugging using separate logger instances for each Thread, but this is slowly becoming a nightmare and I'll soon be drowning into my own logs.
Don't try to debug everything all at once. Narrow your focus to a particular behavior in one thread or pair of threads that interact around some mutex lock. If accessing a shared resource is the problem, set breakpoints around use of that resource (which should be in common code, not all over the place).
If you just want to see that thread 3 completed before thread 1, or that thread 2 used up all its work items and is sitting idle, use logs for that.
You can also use the VS Threads view to see what each thread is doing whenever the process is stopped at any breakpoint on any thread. This can give you some insight into what all the threads are doing at any given instant.
A small tip that might ease your pain is to use Visual Studio to freeze threads that you are not interested in. Then when you tell the debugger to continue, the frozen threads will never execute and will not hit breakpoints and confuse you.
Maybe you can use this method to allow only the threads you are debugging to work. E.g. keep one thread that enqueues and one thread that dequeues active, but freeze everything else.
You can freeze/thaw threads from Visual Studio's Threads window, by right-clicking on a thread.
Write it correctly the first time.
Joking aside, the trick to debugging is to break it down into manageable parts. Tackle one worker task at a time, make absolutely sure it does what it's supposed to.
Once you've done that, debugging issues in the main thread is a lot easier, because you can pretty much ignore the background workers and just presume they're yielding correct results when they should be.
The only place left that's harder to debug than a single-threaded application is the interconnect between the threads, which shouldn't be much more difficult if you're using the libraries the way you should be.
I Stumbled upon a detailed MSDN article about Debugging Multithreaded Applications
wich was of great help. Thanx for all the previous answers that guided me towards the right track.

Breaking single thread

Is it possible to break a single thread in Visual Studio, while other threads will continue their execution?
I have one background thread that does simple data sending/receiving, which I would like to happen, while stepping through my code in some other thread.
open the thread view (Debug->Windows->Threads), right-click the thread you want to suspend, select 'Freeze'. Select 'Thaw' to put it back in a running state.
Generally it's impossible, but there are some things that might work for specific scenarios.
Basic solution
As mentioned elsewhere, repeating the sequence: Freeze, Resume, (wait), Pause, Thaw, Step should result in the behavior you describe, giving other threads the possibility of running in the background while your target thread is halted.
This approach has at least two issues:
It's quite tedious
Your background threads will be suspended anytime the debugger is paused.
Improvements
The first issue may be tackled using a different procedure: Issue a Thread.Sleep(10000) in the Immediate Window, effectively keeping the focused thread occupied while the other threads execute normally. You could even bind that command to a macro.
The second issue can only be tackled by an approach that does not need to pause the debugger. But how would we examine state when the session isn't paused? That's where IntelliTrace comes in, but you may find you need to create custom IntelliTrace events. Drawback of this approach is that you can not manually modify state mid-flight.
Set a counter that does a one up for each thread created and then set your break point to break on a condition and pick a value for that counter. I don't think this will work in all cases, especially PLINQ, but should be doable in a lot of situations.
All i can find to this, is that you can change the behaviour on a process level by the setting
Tools - Options - Debugging - General - Break all processes when one process breaks
but not on a Thread base.
You can always put a conditional break point based on a property of your current thread (like the name or id).
You may also find this usefull : http://www.codeproject.com/Tips/396617/Conditional-Breakpoint-using-Make-Object-Id-featur
This worked for me in VS2008 and should work in a similar way in 2010 at the least

Alternatives to Thread.Sleep() for simulating pauses

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.

Categories

Resources