C# Visual Studio Debugger UI behavior with lock - c#

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.

Related

JetBrain Rider: viewing List<> during debugging

I'm trying to view the content of a List<> during debugging. Unfortunately I can't see them, cause I get the following message within the variables window:
corvalue.GetExactTypeSafe(out type). The object is in a
zombie state. (Exception of HRESULT: 0x8013134F). The error code is
CORDBG_E_OBJECT_NEUTERED, or 0x8013134F.
Does someone know what this means and how I can view the List<>? It's no compilation error cause I can normally run through the code.
sounds like you are using multi-threading. lets start with zombie state.
zombie state is when a thread that was previously started (by another thread) finally finished it work. and additionally this thread didn't return the control to the calling thread. hence, this thread is currently ain't doing anything although it wasn't terminated.This is the source of the name, the thread ain't alive and ain't dead. For more information you can check this post.
You need to simply free up all allocated resources by restarting your program or kill the parent thread\process.
If you keep having the issue in the "interesting code" You can also try to run your program with out multi threading to ensure you wouldn't encounter any zombies along the way. (:

Is it possible for a thread to just die without throwing an exception?

I have a situation on a production machine where a thread in my Windows Service appears simply to die, without throwing an exception. To date my logging hasn't been verbose enough to pinpoint the exact line of code where it is dying; I've deployed a new version with more verbose logging for this purpose. But until I get a smoking gun, my suspicion falls on the line of code where I create a new DB context.
The error is not predictable, except that it tends to happen during periods of high activity, and is often correlated with other threads throwing DB timeout exceptions (hence my suspicion above). Exceptions I can handle. Dead threads I can't.
Any ideas why a thread might die silently, or otherwise simply freeze? Or what to do about it?
EDIT: To be clear, the code is surrounded by a try-catch block, and the catch does some logging (using log4net). So does the "finally". I know it's working because other threads have left logs when they threw exceptions. All that I see in my log is that thread x hits a certain debug point, then is never seen or heard from again, and the work it was supposed to do remains not done.
No, not really (but kind of). Threads don't die, they finish. A thread can finish successfully or by failure--if a thread fails then its exception is stored until it is handled. Depending on how you instantiate the thread it's possible that you "fire and forget", meaning that if an exception occurs you have no code to handle and retrieve it. This is doubly bad, as it results in unreleased resources (they're waiting for you to retrieve and handle the exception).
However, you haven't provided any details of what you've diagnosed. What threading approach/framework are you using (there's quite a few)? Are you watching the processes threads and seeing it suddenly disappear? Are you taking heap snapshots, or attaching to the running process after it appears to have died?
If you have access to the system i would debug it with: Visual Studio 2013 Remote Debugger. This is often a good choice if you can't reproduce the error in your development environment.
Threads do not silently freeze or crash, check whether you have some empty catch blocks in your code or it runs into an infinite loop (or very long timeout at any point).
Maybe you have some code for us.

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.

Visual Studio, debug one of multiple threads

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.

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