I quite often stumble about code that takes too much time for the debugger to evaluate yielding to the following annoying error:
Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.
Usually we can ignore this by just stepping further, making the debugger-thread snyc to our process and then re-evaluate our statement.
However when I attach my source-code to a running, managed process, I´m unable to step any further. As soon as I get the mentioned error, no breakpoints are hit at all nor will "Break all" let me break the execution and see the currently executing statement.
The yellow line produces the error mentioned above. However no breakpoint is hit after continuing, neither by using F10 ("Step over") nor F5 ("Continue"). After this I´m completely unable to debug anything in my entire codebase.
Also when I try to break debugging to see what the process is currently doing no source-code is available nor any dissambly-information, as seen here:
I have a few methods that run one by one in a loop. To show the entire progress after every such method my BackGroundWorker is notified:
void RunTests()
{
foreach(var m in methods)
{
m.Invoke(...);
backgroundWorker1.ReportProgress(1);
}
}
private void InitializeComponent()
{
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.RunTests);
}
The behaviour occurs inside the currently invoked method. I suppose it´s because of the other thread which the BackGroundWorker uses in order to notify the progress to the UI (in my case a progressbar), but that´s just a guess.
Has anyone an explanation or even better a solution which doesn´t need to re-start the process (which as I noticed yields to the exact same behaviour btw.).
This is because the exception is un-handled and Visual Studio cannot move past that line without it being handled in some manner. It is by design.
Continuing in the Visual Studio debugger after an exception occurs
Related
I need to terminate the whole script execution if command let encounters the error. The whole script after that must never execute. In my case, If I use ThrowTerminatingError, it just stops the current commandlet to be executed further and the rest of the script executes which I don't want.
I already used "PipelineStoppedException" but this doesn't tell anything in the error stream and no exception can be a catch. Because Invoke call successfully terminates.
How can I achieve this? I want to terminate the whole script execution with the exception message. Following is the C# code which I am using from commandlet but it is still allowing rest of scripts to continue execution further.
Edit
protected override void BeginProcessing()
{
base.BeginProcessing();
if (SomeLogicTrue())
{
var errorRecord = PowershellErrorHandler.GetErrorRecord(new PipelineStoppedException("access is not supported for this context."), "InvalidExecutionContext");
ThrowTerminatingError(errorRecord);
}
}
Set the error action preference to "Stop" at the beginning of your script.
$ErrorActionPreference = "Stop"
Now, even if the script throws a none terminating error, it will stop at once.
I'd suggest you to read An Introduction to Error Handling in PowerShell as well.
TL;DR - Is there a 'recursive' [DebuggerStepThrough]?
Is there an attribute I can use on a method so that when using Debug > Break All on an idle WinForms form and then stepping into Application.Run(), such that no breakpoint will be triggered on that method or anything it calls, when an event calls that method?
Here's some simple example code as an illustration of the problem¹:
static void Main() {
Application.Run(new MyForm()); //I step (F11) into here to wait for events of interest
}
string GetSome {
get { //I don't want to wind up on a breakpoint here
return "Some"; //as a result of OnActivated() being called!
} //But I *DO* want to be able to step in here otherwise,
} //(e.g. as a result of OnClick() being called.²
[DebuggerStepThrough] //Not interested in this event or anything it calls
protected override void OnActivated(EventArgs e){
string come = GetSome;
}
protected override void OnClick(EventArgs e){ //But I *AM* interested in this event
string come = GetSome;
}
What I'm doing: Once my WinForms form has fully initialized, got focus, and is now idle (no queued messages in message loop) (marker 1), I pause the idle form with Debug > Break All. The form is in it's idle loop, so the debugger shows the topmost stack frame as [External Code], with the previous stack frame being the Application.Run() line. I then hit F11 (Step Into). The form's message loop is resumed and the form re-activates and gets focus. (marker 2) The debugger will now pause as soon as a managed frame comes up at the top of the stack - e.g. once one of the events in the above code occurs. (marker 3) The form re-activating causes OnActivated() to get called.
Desired behavior:
I want the debugger to ignore OnActivated() and whatever else it may call. Once I click the resumed form, I want the debugger to pause on OnClick(), since the debugger is waiting for a managed frame to come up to the top of the stack.
What actually happens:
The debugger ignores OnActivated() (since it's marked as [DebuggerStepThrough]) - good, but pauses in the GetSome getter - bad. At this point:
If I step through the GetSome getter, the form re-activates again, and I'm back at marker 2 and I'm in a loop.
If I step out (Shift+F11) of the GetSome getter, it has the same effect as pressing F5 - the execution of the program is completely resumed with the debugger no longer looking to pause at the next managed stack frame. I'm back at marker 1.
Interestingly, the debugger is actually ignoring the "Debug > Options > Debugging > General > Step over properties and operators" option at marker 3. If I step into (F11) Application.Run() manually when starting the form, with "Step over properties and operators" enabled, the debugger does not pause on the GetSome getter from OnActivated() being called!
¹ There are no explicit breakpoints set anywhere in the code. In the actual code I'm working on, I'm trying to get the debugger to ignore just a few particular redraw events (and whatever methods & accessors they call from other classes) while being able to use "Break All + F11" as a shortcut for stepping into whatever next event may occur (there are dozens of possibilities) without having to set an explicit breakpoint on each one.
² The reason I can't just mark all other methods that 'uninteresting' events call with the [DebuggerStepThrough] attribute as well is twofold: The few 'uninteresting' events I have call hundreds of other methods in all - that's a lot of refactoring and visible clutter to add; and since, of course, I would lose the ability to step through those methods when I actually need to when debugging.
I refactored my application a while ago and since then I've been having problems with debugging using Visual Studio 2010.
My application works as expected while not debugging (not stepping through the application. An attached debugger does not cause any issues). However, when a breakpoint is triggered and I start to step through the app, Visual Studio and the app both hang after at most 3-4 steps.
To emphasize this point even more: It works well with my customers and regardless of whether I start it from Visual Studio or stand-alone - as long as no break point is triggered.
It does not matter where in the code I place the break point.
IDE: Visual Studio 2010 x64
Platform: .NET 4.0
The refactoring included a lot of cross-thread calls to BeginInvoke - all channeled through the following method:
public static void BeginInvokeIfRequired(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
There is not a single call to Control.Invoke() in the project.
Is there something wrong with the above method?
Additionally, I'd appreciate any hints on how you would track down this bug. My current approach is to add output to the console and selectively deactivating parts of the code.
I would suspect that in some cases the code you show poses a problem since InvokeRequired lies in case IsHandleCreated is false - it returns false even if you are not on the GUI thread.
For reference see http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx .
The following code throws an exception instead of hanging... the fact that it "works as expected" when no breakpoint is hit might be a result of the debugger freezing all threads on hitting a breakpoint which in turn might lead to a different order of execution etc.
Altogether this means: you might have some "race condition" in your code where BeginInvokeIfRequired is called on a freshly created control before that control has a Handle. This can even be some 3rd-party code you use...
public static void BeginInvokeIfRequired(this Control control, Action action)
{
if (control.IsHandleCreated)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
else {
// in this case InvokeRequired might lie !
throw new Exception ( "InvokeRequired is possibly wrong in this case" );
}
}
I've been messing with VS 2010 debugging settings, trying to get stepping into the .NET Framework working. Well, I can't get it to work. I've also tried the Reflector VS plugin and that was working at one point.
Then I randomly started getting this error:
This only happens when I have a breakpoint on a line that calls IEnumerable<T>.ToList(). If I try to step-over or step-into on that line where my breakpoint is set, I get this error dialog and my debugging session ends.
If I move the breakpoint to the line below, the debugger makes it past the ToList() call!
I've tried the following to no avail:
Removing the Reflector plugin.
Undoing my changes in the Tools > Options > Debugging window (unchecked the option to step into the .NET Framework; unchecked the source server option; checked the just my code option).
Unchecked Microsoft Source Server in the Tools > Options > Debugging > Symbols window.
Cleared the symbol cache.
What is going on?
Because this was the first place I came to when I searched for an answer, I'll add what I found out.
In my case, I had the debugger set up in the solution to start multiple projects. For some reason this setting was changed by Visual Studio so that no project was starting. Correcting the setting in the solution immediately solved the problem.
The problem was not difficult to solve, but the error message was more than a bit irritating.
I've just found this answer useful. All I did was change my start-up project to another, and back to normal.
My project probably lost this setting somewhere, and resetting it made it available again.
It was a ToString() override that make the debugger crash ! (After the evaluation the debugger will show you the result with the ToString() method). And if you get an exception in the ToString(), you will never catch an exception because you cannot code them on the debugger behaviour.
I've got this answer from msdn
I suffered from same problem....
I found one solution which heard uncommon....
The debugger cannot continue running the process.Process was terminated
While debugging your code step by step , you will find the line , from where error redirecting.
If you are using " ToString() " anywhere in that file ,please remove that .
Instead of the ,you can use Value / Text .
It works fine.
............
If you were not used ToString() any where in program , then reload project copy by removing completely.
I had the same problem. I traced it down to a class(step-by-step debugging) and finally to a property(commenting all the code, then step-by-step uncommenting).
this property returned a typed dataSet from a table.Dataset
private typedDataSet myDataSet
{
return this.DataSet as typedDataSet;
}
this was in a DataTable partial class.
After I removed this property everything went OK.
I ran into this issue with a code bug from copy/paste. Instead of get/setting the private member variable, I did a get/set on itself. When I referenced the property in other code the debugger terminated (2010):
public bool ProdToDeve
{
get { return ProdToDeve; } // <= missing underbar
set { ProdToDeve = value; }
}
private bool _ProdToDeve = false;
This message will also show up when you're trying to debug a Xamarin solution but you have a class library selected as the startup project instead of your application porject.
It occurred to me when I was doing the following:
throw new Exception(timeout.TotalSeconds + " second(s)");
That's because timeout.TotalSeconds.ToString() which indeed is an override method for an object of type double, was throwing a Parameter not valid exception.
Finally, for safety I ended up doing the following:
throw new Exception(System.Convert.ToString(timeout.TotalSeconds));
Well, typically, this is also the kind of error message you can get in a multi-threads context. In brief, it involves concurrency : make sure that your resource accesses are always secured.
In my case, I got this error message when I forgot to secure resource accesses at some places within my code. To solve this issue, I just had to decorate the critical sections with a lock instruction (on the concerned resource). I hope this will help those who are in this context.
I'm facing an issue which I can't seem to wrap my head around.
private void IndexEntityType(Type targetType, bool onlyNew)
{
Logger.Debug("generating index for {0}", targetType);
using (var wrapper = SessionWrapper.For(targetType, true))
{
var session = wrapper.Session;
session.FlushMode = FlushMode.Never;
session.CacheMode = CacheMode.Ignore;
var entities = GetEntities(targetType, onlyNew, session);
Logger.Debug("Indexing {0} entities", entities.Count);
// Create a Full Text session.
using (var fullTextSession = Search.CreateFullTextSession(session))
using (var transaction = fullTextSession.BeginTransaction())
{
fullTextSession.CacheMode = CacheMode.Ignore;
foreach (var entity in entities)
{
fullTextSession.Index(entity);
}
try
{
transaction.Commit();
}
catch (Exception ex)
{
Logger.Error("could not commit fulltext session transaction", ex);
}
}
Logger.Debug("generated index for {0}", targetType);
}
ReQueueTimers(onlyNew);
}
I'm trying to debug this and have set breakpoints at the first row (Logger.Debug) and the last row (ReQueueTimers).
However, when stepping through the code, the last call (ReQueueTimers(onlyNew)) is never invoked, nor hitting the breakpoint. How can that be? Does the compiler "remove it when optimizing" somehow?
Does anyone have any hint on what might trigger this behavior?
EDIT: This is run in multiple threads if that might have anything to do with it.
It could be that your code is throwing an exception - if anything other than the transaction.Commit() throws an exception, the ReQueueTimers call won't be made. You could prove this by getting Visual Studio to break on all CLR exceptions - in the Debug menu, select "Exceptions", and check the "Thrown" box on the "Common Language Runtime Exceptions" row. Then start debugging again.
On the other hand, I have sometimes had Visual Studio just give up stepping through code halfway through debugging a method. Maybe this is the cause - it might have something to do with multiple threads. If you remove the first breakpoint and leave the one on the ReQueueTimers call, does this make any difference?
As a little addition to what Graham said:
If you run on multiple threads and an exception is thrown on that thread and is not caught, the thread is aborted.
I had the very same issue from 2 days and banged my head dead until... I found this somewhere on the net:
Make sure that your target code actually builds when you build your solution/project. To do that, go to Build->Configuration Manager and make sure the corresponding project is checked (In the rightmost column).
Mind you, for some misterious reason that only Gates knows, the box was unchecked!