Visual Studio, debug one of multiple threads - c#

I have an application with 4 threads working the same code. However, when I step it jumps between the different threads. How can I lock it to one thread so the other threads are ignored for debugging?

Yes.
In the Threads window (Debug -> Windows -> Threads) right-click the thread you want and select "switch to thread".
You can also choose "freeze" on the threads you don't want to debug in order to keep them from running. Don't forget to "thaw" them if you expect them to do work, however.
Further reading.

Single stepping through a single thread seems to be mostly fixed in VS 2012 (with some caveats you can see in my link below). Breakpoints are a pain.
Freezing and thawing threads is the usual workaround, as previous answers have stated, but it's tedious, and it can cause hangs when your thread waits on another thread that's frozen. These can be tough to recover from without losing your place in your thread of interest.
Another useful workflow is to apply a thread filter on your breakpoints, also stated in some of the answers:
Create a breakpoint, right click on the breakpoint, click Filter, and enter ThreadId = 7740 (your thread id from the threads window).
This can be very tedious.
My suggestion to Microsoft is to fix single stepping (and variations of it) to never switch threads unless an explicit breakpoint is hit in another thread. They should also add a shortcut (maybe Ctrl-F9) to create a breakpoint with the current thread id as its filter. This would make the second workflow much more convenient.
Vote up the suggestion if you agree this would be useful, or add your own suggestions:
https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/8543248-make-the-debugger-stick-to-the-current-thread-inst

You could also put a conditional breakpoint in your code and put the thread.Id == [someValue] or Thread.Name == "[Somename]" in the breakpoint condition...

A much quicker workaround exists for simple cases - see comments in Steve's link.
the debugger will only ever complete a step on the thread from which the step was originated. So if you hit a breakpoint, disable it, and then begin stepping you should not stop on a different thread. If you have other breakpoints in your application and another thread hits one, then you will be debugging in the mixed thread state as described
So in my case once the various threads started hitting my breakpoint I just hit Continue a few times until I identified the call I was looking for - then removed the breakpoint and stepped through the rest of the code while remaining on the same thread without interference from the rest of them.
This obviously becomes a problem if you have multiple breakpoints that you want to keep, etc. - but again for simple cases this is much easier to do.

This strongly resembles a very similar problem in Visual Studio 2008 SP1. It was fixed with a post-SP hotfix. But there's other evidence that the hotfix didn't get incorporated into the code base, this feedback item was also a problem. It isn't that unusual for hotfixes to not get integrated back.
There isn't a feedback item that exactly describes your problem, at least that I can find. I'd recommend you file one. Given the usual trouble with reproduce bugs like this, I'd strongly recommend you include a reproduction project that exhibits this problem with instructions on how to reproduce the issue.
There is a workaround of sorts for your issue, you could go into Debug + Windows + Threads, right-click the threads you don't want to debug and select Freeze. Don't forget to Thaw them later.
These bugs were fixed again in Visual Studio 2010 Service Pack 1.

5. Step through one single thread without jumping around
How often are you debugging multithreaded code, when you hit your
first breakpoint, take a step, and then suddenly you are stopped with
the yellow arrow on another thread? The unexpected behavior comes from
the breakpoint still being set and consequently being hit. By default,
the debugger will stop on a breakpoint any time it is hit. This means
that when you take a step, all threads are allowed to run, and one of
your running threads hit this breakpoint before the step completes on
your current thread. Next time you get in this situation try this:
Disable or delete the breakpoint that has been hit by the new thread the debugger switched to.
Press Continue (F5)
Observe how your first initial step on that first thread completes and now is the active debugging context.
Since your breakpoints are deleted or disabled, you can continue stepping on that single thread without interruption.
7 lesser known hacks for debugging in Visual Studio

I'm Using Visual Studio Professional 2017, and I use the Threads window to selectively freeze and thaw threads. Usually I have multiple threads of the same code and I only want to freeze them, not others. I actually like the MS Threads window because I can select a subset of threads to freeze. I group the threads by name and can then freeze all the ones running the same code as I am debugging while letting the remaining threads run. I tried using the Erwin Mayer extension, and it worked very well, but it freezes all threads except the one I am running, and I sometimes get into a situation when debugging does not hit the breakpoint I think it should, then because all of the other threads are stopped and the application seems halted. Hitting the pause button, and unfreezing threads in the threads window fixes that issue.

Related

Visual studio, F11, only stepping interested in what a particular thread is doing?

Im just wondering if anyone knows if its possible to setup the debuger such that F11 is only interested in a single thread? I have two threads running atm but im only interested in 1 of them. As such i dont want the screen to keep jumping further up the page to show me what the 1st thread is doing. Id like to set it up such that it only shows what the 2nd thread is doing.
Any pointers would be appreciated, thanks.
One way to do it would be to freeze the thread you are not interested in.
In Visual Studio, show the "Threads" window, available from the Debug->Windows menu.
Then, while you are tracing using F11, if the debugger breaks in the thread you are not interested in, find this thread in the threads window, right-click it and choose the "Freeze" option in the context menu.
Now when you continue to trace using F10 or F11, you will never hit breakpoints in the frozen thread.
Note that the frozen thread will not be executing at all, so if you do need it to do some work while you are debugging, you may need to unfreeze and freeze it again from time to time.
If you open the debugger's "Threads" window you'll see that there's a "Just My Code" flag for each thread. I've found that if you set the flag for only the current thread that you're stepping through, the "Step into" (F11) and "Step over" (F10) functions seem to target only that thread. While this targets native threads, it works just as well for managed code using threads.
However, the functionality can be pretty fragile if you're not careful - breakpoints will still break for any thread (unless the breakpoint is filtered to be only for the thread of interest). And if another thread is in the middle of being stepped before you set this flag, that thread may still 'interact' with the debugger while you're trying to step through the current thread. So you'll need to carefully manage your breakpoints while using this feature.
However, all-in-all it seems to work really well.
Note that I think the terminology is quite confusing since "Just My Code" is also used to describe a managed debugger feature for setting the debugger to not bother stepping into 'non-user' code (which is controlled by attributes on methods). The native thread "Just My Code" is something different, and I actually can't find much in the way of documentation (How to: Flag and Unflag Threads). This particular behavior of targeting a single thread for stepping doesn't seem to be mentioned - I stumbled on it by accident.

C# Visual Studio Debugger UI behavior with lock

I have a block of code in a lock:
lock (obj)
{
//...
}
I also have a property that locks on that same object. Simple enough scenario. My question is, if I put a breakpoint inside my locked block of code, and then examine the property in the Visual Studio debugger, what will happen? Will the debugger deadlock until I continue executing after breakpoint (or kill visual studio/debugging)? Or will the debugger simply not show any data for the property (grabbing data in background thread from UI?)
The reason I ask is I've got a property specifically (and only) for debugging purposes; I'm OK with it occasionally not showing data when this scenario happens, but having crashed the debugger (and visual studio) many a time with bad debugger attributes, I'd rather avoid code that could at some point hamper my debugging efforts when that's what I'm trying to aid to begin with!
I plan on testing this at some point when I've got some more time, but was hoping for a quicker answer from someone who might know better.
Yes, the debugger executes watch expressions on a separate worker thread that's running inside the process. Which will hit the lock in your property getter and block. The debugger puts up with that for 5 seconds, then declares the watch expression unusable and displays "Function evaluation timed out".
The debugger then gets grumpy, not much it can do with that blocked thread, you'll commonly see "Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation." Which is good advice.
No the debugger will show you the properties of the object even if it is within a lock() block.
Lock()ing the object does not actually prevent any access to the object - it simply creates a semaphore that will block any other code that attempts to lock the same object until the lock is released.
My experience is that the VS.NET debugger does freeze from time to time, but it must have some deadlock detection and debug optimizations to avoid these types of issues.

Network program blocking

I am working on a network project which uses TCPListener and TCPClient. I have two almost identical instances of my program running on two different computers, but for some reason one of the instances works fine while the other one blocks somewhere.
What I'm wondering is if there is any way to debug what exactly is going on inside. The problem being that breakpoints don't work since they just show the execution of one thread and nothing else. I tried Pausing the program and it shows me the line Application.Run (...) and I have no way of getting in.
Debugging this is a nightmare, and any advice would be appreciated.
PM
In the toolbar of Visual Studio, you have a dropdown list with the threads. You can use this to switch to the current halting point in another thread after pausing the execution.
MSDN: How to: Switch to Another Thread While Debugging

How could I get to know the resources occupied by a .NET thread?

I am developing a multi-thread application and one of my threads is somehow blocked by something and thus it will occupy some resource such as a file forever. Is there a way to find out which thread is being blocked and more important what resouce is being held by that thread?
At last and as usual, thanks for your patience and reply. :)
---------new progress----------
Since all the resouces on the windows platform are accessed via "handles". I am thinking if there is a way to list all the handles a .NET thread is holding?
When you Create the Threads, you can Set a Name for each thread just before you start it. You can then use these in the Debugger to identify the Thread in question.
Then when your program doesn't close, you jump up to the debugger and Hit Pause, you can then via the active threads. Debug->Windows->Threads (CTRL-ALT+H)
If your threads are not critical, and you just want the system to Close upon Completion you can set .IsBackground on the thread and you don't need to perform any special operations to get your thread to close, often though this may lead to other conditions you were not expecting.
I personally also use System.Threading.AutoResetEvent(duration) instead of Sleep(duration) because if I wish to exit, I set mIsRunning=false then set the event which will cause the Stopping of the Event to Wake up, but Exit Immediately. A Sleep has to finish before it resumes.
The new Concurrency Profiler in Visual Studio 2010 was built to answer and solve this type of question.
Resource Contention Concurrency Profiling in Visual Studio 2010 – Performance Investigation Flows
I recommend downloading the trial version if you don't already have Visual Studio 2010. You won't be disappointed. :)
If you are familiar with dump analysis using WinDbg, you can also capture a hang dump when this issue happens, and then manually analyze the dump to see which thread hangs and why.
http://blogs.msdn.com/tess/archive/tags/Performance+issues+and+hangs/default.aspx

Knowing At what point the application freezes

I am developing a WinForm multithreaded application with C#.
Sometimes it happens that my application hangs, or freezes or blocks.
When this happens and I am running in DEBUG mode, is there anyway to understand at what line of code my application is currently? Since it is freezed I expect to find a point where the application is locked or blocked or whatever.
Is it possible to do that someway?
When It is freezed I tried to open the CALL STACK window, but this doesn't display any info; is there some action that I might do? Some "pause and check" or whatever?
You may need to open the Threads window, and change the current thread. While debugging, choose Debug->Break All, and open the Threads window. If you go through each thread, by double clicking on the thread, you should be able to investigate the call stack for each thread.
That being said, if you can run your program in VS 2010 - this gets a lot easier. In VS 2010, you can use the new Concurrency Profiler, and run your code under the Concurrency Profiler with the option to Visualize the Behavior of a multithreaded application. Once your application locks up, kill it, and let the profiler churn -
Eventually, you'll get a diagram which shows each thread in your program, and when they're locked. The callstack for each blocked thread will be shown, as well as what lock is being held (with the line of source code). This makes it very easy to track down a dead lock.
When debugger is attached go to Debug menu and choose 'Break All'... Then you can examine call stacks for all thread.
You could press pause and see where it ends up (use the aforementioned call stack window). Chances are however that you'll end up in native code. You could try to step out a bit or just look at the stack for a managed function to debug.
Alternatively you could put a breakpoint after the application "freezes" and try to pinpoint a loop that doesn't end.
Both the above are assuming your application is busy (100% cpu usage). If your application is however stuck in a dead lock or just plain waiting for a mutex that won't tick, you'll have to manually re-read your code and try to figure it out on your own.

Categories