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" );
}
}
Related
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
When I create a new project, I get a strange behavior for unhandled exceptions. This is how I can reproduce the problem:
1) create a new Windows Forms Application (C#, .NET Framework 4, VS2010)
2) add the following code to the Form1_Load handler:
int vara = 5, varb = 0;
int varc = vara / varb;
int vard = 7;
I would expect that VS breaks and shows an unhandled exception message at the second line. However, what happens is that the third line is just skipped without any message and the application keeps running.
I don't have this problem with my existing C# projects. So I guess that my new projects are created with some strange default settings.
Does anyone have an idea what's wrong with my project???
I tried checking the boxes in Debug->Exceptions. But then executions breaks even if I handle the exception in a try-catch block; which is also not what I want. If I remember correctly, there was a column called "unhandled exceptions" or something like this in this dialog box, which would do excatly what I want. But in my projects there is only one column ("Thrown").
This is a nasty problem induced by the wow64 emulation layer that allows 32-bit code to run on the 64-bit version of Windows 7. It swallows exceptions in the code that runs in response to a notification generated by the 64-bit window manager, like the Load event. Preventing the debugger from seeing it and stepping in. This problem is hard to fix, the Windows and DevDiv groups at Microsoft are pointing fingers back and forth. DevDiv can't do anything about it, Windows thinks it is the correct and documented behavior, mysterious as that sounds.
It is certainly documented but just about nobody understands the consequences or thinks it is reasonable behavior. Especially not when the window procedure is hidden from view of course, like it is in any project that uses wrapper classes to hide the window plumbing. Like any Winforms, WPF or MFC app. Underlying issue is Microsoft could not figure out how to flow exceptions from 32-bit code back to the 64-bit code that triggered the notification back to 32-bit code that tries to handle or debug the exception.
It is only a problem with a debugger attached, your code will bomb as usual without one.
Project > Properties > Build tab > Platform target = AnyCPU and untick Prefer 32-bit. Your app will now run as a 64-bit process, eliminating the wow64 failure mode. Some consequences, it disables Edit + Continue for VS versions prior to VS2013 and might not always be possible when you have a dependency on 32-bit code.
Other possible workarounds:
Debug > Exceptions > tick the Thrown box for CLR exceptions to force the debugger to stop at the line of code that throws the exception.
Write try/catch in the Load event handler and failfast in the catch block.
Use Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) in the Main() method so that the exception trap in the message loop isn't disabled in debug mode. This however makes all unhandled exceptions hard to debug, the ThreadException event is pretty useless.
Consider if your code really belongs in the Load event handler. It is very rare to need it, it is however very popular in VB.NET and a swan song because it is the default event and a double-click trivially adds the event handler. You only ever really need Load when you are interested in the actual window size after user preferences and autoscaling is applied. Everything else belongs in the constructor.
Update to Windows 8 or later, they have this wow64 problem solved.
In my experience, I only see this issue when I'm running with a debugger attached. The application behaves the same when run standalone: the exception is not swallowed.
With the introduction of KB976038, you can make this work as you'd expect again. I never installed the hotfix, so I'm assuming it came as part of Win7 SP1.
This was mentioned in this post:
The case of the disappearing OnLoad exception – user-mode callback exceptions in x64
Here's some code that will enable the hotfix:
public static class Kernel32
{
public const uint PROCESS_CALLBACK_FILTER_ENABLED = 0x1;
[DllImport("Kernel32.dll")]
public static extern bool SetProcessUserModeExceptionPolicy(UInt32 dwFlags);
[DllImport("Kernel32.dll")]
public static extern bool GetProcessUserModeExceptionPolicy(out UInt32 lpFlags);
public static void DisableUMCallbackFilter() {
uint flags;
GetProcessUserModeExceptionPolicy(out flags);
flags &= ~PROCESS_CALLBACK_FILTER_ENABLED;
SetProcessUserModeExceptionPolicy(flags);
}
}
Call it at the beginning of your application:
[STAThread]
static void Main()
{
Kernel32.DisableUMCallbackFilter();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
I've confirmed (with the the simple example shown below) that this works, just as you'd expect.
protected override void OnLoad(EventArgs e) {
throw new Exception("BOOM"); // This will now get caught.
}
So, what I don't understand, is why it was previously impossible for the debugger to handle crossing kernel-mode stack frames, but with this hotfix, they somehow figured it out.
As Hans mentions, compile the application and run the exe without a debugger attached.
For me the problem was changing a Class property name that a BindingSource control was bound to. Running without the IDE I was able to see the error:
Cannot bind to the property or column SendWithoutProofReading on the
DataSource. Parameter name: dataMember
Fixing the BindingSource control to bind to the updated property name resolved the problem:
I'm using WPF and ran into this same problem. I had tried Hans 1-3 suggestions already, but didn't like them because studio wouldn't stop at where the error was (so I couldn't view my variables and see what was the problem).
So I tried Hans' 4th suggestion. I was suprised at how much of my code could be moved to the MainWindow constructor without any issue. Not sure why I got in the habit of putting so much logic in the Load event, but apparently much of it can be done in the ctor.
However, this had the same problem as 1-3. Errors that occur during the ctor for WPF get wrapped into a generic Xaml exception. (an inner exception has the real error, but again I wanted studio to just break at the actual trouble spot).
What ended up working for me was to create a thread, sleep 50ms, dispatch back to main thread and do what I need...
void Window_Loaded(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Thread.Sleep(50);
CrossThread(() => { OnWindowLoaded(); });
}).Start();
}
void CrossThread(Action a)
{
this.Dispatcher.BeginInvoke(a);
}
void OnWindowLoaded()
{
...do my thing...
This way studio would break right where an uncaught exception occurs.
A simple work-around could be if you can move your init code to another event like as Form_Shown which called later than Form_Load, and use a flag to run startup code at first form shown:
bool firstLoad = true; //flag to detect first form_shown
private void Form1_Load(object sender, EventArgs e)
{
//firstLoad = true;
//dowork(); //not execute initialization code here (postpone it to form_shown)
}
private void Form1_Shown(object sender, EventArgs e)
{
if (firstLoad) //simulate Form-Load
{
firstLoad = false;
dowork();
}
}
void dowork()
{
var f = File.OpenRead(#"D:\NoSuchFile756.123"); //this cause an exception!
}
Recently we came across some legacy WinForms application we needed to update with some new features. While expert testing the application, it was found that some old functionality is broken. Invalid cross-thread operation. Now before you take me for a newbie, I do have some experience with Windows Forms applications. I'm no expert, but I consider myself experienced with threading and know exactly how to manipulate GUI components from a worker thread.
Apparently the one who wrote this piece of software did not and just set UI control properties from a background thread. Of course it threw the usual exception, but it was encased in an all-catching try-catch block.
I spoke with a stakeholder to find out how long this functionality had been broken, and turned out it was fine before. I couldn't believe that, but he demoed me that the function actually works in PROD.
So our unrelated updates "broke" the software in three places, but I can't get my head around how it could have worked in the first place. According to source control, the bug has always been there.
Of course we updated the application with proper cross-thread UI handling logic, but now I'm in the unlucky position of having to explain to stakeholders with not much tech background why something that can't have worked like ever, did work fine until we did some unrelated changes to the system.
Any insights would be appreciated.
One more thing that came to mind: in two of the cases the background thread updated a ListView control that was on a non-selected (and thus non-displayed) TabPage control. The third time it was standard Label control (text property was set) that was initially empty and gets a Text assigned according to what the background thread finds.
Here's some code for you, very similar to the one we found:
private void form_Load(object sender, System.EventArgs e)
{
// unrelated stuff...
ThreadStart ts = new ThreadStart(this.doWork);
Thread oThread = new Thread(ts);
ts.Start();
// more unrelated stuff ...
}
public void doWork()
{
string error = string.Empty;
int result = 0;
try
{
result = this.service.WhatsTheStatus(out error); // lengthy operation
switch (result)
{
case 1:
this.lblStatus.Text = "OK";
break;
case -1:
this.lblStatus.Text = "Error";
this.lblError.Text = error;
break;
default:
this.lblStatus.Text = "Unknown";
break;
}
}
catch
{
}
}
Unfortunately I saw lblStatus being updated in the production environment and it isn't referenced from anywhere else in the entire application (except the Designer generated stuff, of course).
That is because cross-thread access exceptions are not guaranteed to be thrown when you run code without debugger (in windows forms). Read this for example: https://msdn.microsoft.com/en-us/library/vstudio/ms171728%28v=vs.110%29.aspx:
The .NET Framework helps you detect when you are accessing your controls in a manner that is not thread safe. When you are running your application in the debugger, and a thread other than the one which created a control tries to call that control, the debugger raises an InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on."
This exception occurs reliably during debugging and, under some circumstances, at run time. You might see this exception when you debug applications that you wrote with the .NET Framework prior to the .NET Framework 2.0. You are strongly advised to fix this problem when you see it, but you can disable it by setting the CheckForIllegalCrossThreadCalls property to false. This causes your control to run like it would run under Visual Studio .NET 2003 and the .NET Framework 1.1.
You can check this yourself by writing simple winforms application, set form title from another thread and see exception is thrown. Then run same application without debugger attach and see how form title will happily change without any problems.
When I create a new project, I get a strange behavior for unhandled exceptions. This is how I can reproduce the problem:
1) create a new Windows Forms Application (C#, .NET Framework 4, VS2010)
2) add the following code to the Form1_Load handler:
int vara = 5, varb = 0;
int varc = vara / varb;
int vard = 7;
I would expect that VS breaks and shows an unhandled exception message at the second line. However, what happens is that the third line is just skipped without any message and the application keeps running.
I don't have this problem with my existing C# projects. So I guess that my new projects are created with some strange default settings.
Does anyone have an idea what's wrong with my project???
I tried checking the boxes in Debug->Exceptions. But then executions breaks even if I handle the exception in a try-catch block; which is also not what I want. If I remember correctly, there was a column called "unhandled exceptions" or something like this in this dialog box, which would do excatly what I want. But in my projects there is only one column ("Thrown").
This is a nasty problem induced by the wow64 emulation layer that allows 32-bit code to run on the 64-bit version of Windows 7. It swallows exceptions in the code that runs in response to a notification generated by the 64-bit window manager, like the Load event. Preventing the debugger from seeing it and stepping in. This problem is hard to fix, the Windows and DevDiv groups at Microsoft are pointing fingers back and forth. DevDiv can't do anything about it, Windows thinks it is the correct and documented behavior, mysterious as that sounds.
It is certainly documented but just about nobody understands the consequences or thinks it is reasonable behavior. Especially not when the window procedure is hidden from view of course, like it is in any project that uses wrapper classes to hide the window plumbing. Like any Winforms, WPF or MFC app. Underlying issue is Microsoft could not figure out how to flow exceptions from 32-bit code back to the 64-bit code that triggered the notification back to 32-bit code that tries to handle or debug the exception.
It is only a problem with a debugger attached, your code will bomb as usual without one.
Project > Properties > Build tab > Platform target = AnyCPU and untick Prefer 32-bit. Your app will now run as a 64-bit process, eliminating the wow64 failure mode. Some consequences, it disables Edit + Continue for VS versions prior to VS2013 and might not always be possible when you have a dependency on 32-bit code.
Other possible workarounds:
Debug > Exceptions > tick the Thrown box for CLR exceptions to force the debugger to stop at the line of code that throws the exception.
Write try/catch in the Load event handler and failfast in the catch block.
Use Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) in the Main() method so that the exception trap in the message loop isn't disabled in debug mode. This however makes all unhandled exceptions hard to debug, the ThreadException event is pretty useless.
Consider if your code really belongs in the Load event handler. It is very rare to need it, it is however very popular in VB.NET and a swan song because it is the default event and a double-click trivially adds the event handler. You only ever really need Load when you are interested in the actual window size after user preferences and autoscaling is applied. Everything else belongs in the constructor.
Update to Windows 8 or later, they have this wow64 problem solved.
In my experience, I only see this issue when I'm running with a debugger attached. The application behaves the same when run standalone: the exception is not swallowed.
With the introduction of KB976038, you can make this work as you'd expect again. I never installed the hotfix, so I'm assuming it came as part of Win7 SP1.
This was mentioned in this post:
The case of the disappearing OnLoad exception – user-mode callback exceptions in x64
Here's some code that will enable the hotfix:
public static class Kernel32
{
public const uint PROCESS_CALLBACK_FILTER_ENABLED = 0x1;
[DllImport("Kernel32.dll")]
public static extern bool SetProcessUserModeExceptionPolicy(UInt32 dwFlags);
[DllImport("Kernel32.dll")]
public static extern bool GetProcessUserModeExceptionPolicy(out UInt32 lpFlags);
public static void DisableUMCallbackFilter() {
uint flags;
GetProcessUserModeExceptionPolicy(out flags);
flags &= ~PROCESS_CALLBACK_FILTER_ENABLED;
SetProcessUserModeExceptionPolicy(flags);
}
}
Call it at the beginning of your application:
[STAThread]
static void Main()
{
Kernel32.DisableUMCallbackFilter();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
I've confirmed (with the the simple example shown below) that this works, just as you'd expect.
protected override void OnLoad(EventArgs e) {
throw new Exception("BOOM"); // This will now get caught.
}
So, what I don't understand, is why it was previously impossible for the debugger to handle crossing kernel-mode stack frames, but with this hotfix, they somehow figured it out.
As Hans mentions, compile the application and run the exe without a debugger attached.
For me the problem was changing a Class property name that a BindingSource control was bound to. Running without the IDE I was able to see the error:
Cannot bind to the property or column SendWithoutProofReading on the
DataSource. Parameter name: dataMember
Fixing the BindingSource control to bind to the updated property name resolved the problem:
I'm using WPF and ran into this same problem. I had tried Hans 1-3 suggestions already, but didn't like them because studio wouldn't stop at where the error was (so I couldn't view my variables and see what was the problem).
So I tried Hans' 4th suggestion. I was suprised at how much of my code could be moved to the MainWindow constructor without any issue. Not sure why I got in the habit of putting so much logic in the Load event, but apparently much of it can be done in the ctor.
However, this had the same problem as 1-3. Errors that occur during the ctor for WPF get wrapped into a generic Xaml exception. (an inner exception has the real error, but again I wanted studio to just break at the actual trouble spot).
What ended up working for me was to create a thread, sleep 50ms, dispatch back to main thread and do what I need...
void Window_Loaded(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Thread.Sleep(50);
CrossThread(() => { OnWindowLoaded(); });
}).Start();
}
void CrossThread(Action a)
{
this.Dispatcher.BeginInvoke(a);
}
void OnWindowLoaded()
{
...do my thing...
This way studio would break right where an uncaught exception occurs.
A simple work-around could be if you can move your init code to another event like as Form_Shown which called later than Form_Load, and use a flag to run startup code at first form shown:
bool firstLoad = true; //flag to detect first form_shown
private void Form1_Load(object sender, EventArgs e)
{
//firstLoad = true;
//dowork(); //not execute initialization code here (postpone it to form_shown)
}
private void Form1_Shown(object sender, EventArgs e)
{
if (firstLoad) //simulate Form-Load
{
firstLoad = false;
dowork();
}
}
void dowork()
{
var f = File.OpenRead(#"D:\NoSuchFile756.123"); //this cause an exception!
}
I've followed this advice to get debugging working for NUnit tests.
http://www.blackwasp.co.uk/NUnitCSharpExpress.aspx
However, i have several tests that do Assert.Throws<...>, which causes the debugger to break when the exception i'm testing for occurs, when really i want it to break if an exception occurs outside of those calls.
How can i get the debugger to ignore exceptions caused from within these kinds of methods?
EDIT: I've event tried the below, which doesn't work!
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
try
{
Assert.Throws<ArgumentNullException>(() => new CachedStreamingEnumerable<int>(null));
// This still throws and stops be being able to debug tests called after this one
}
catch
{
}
}
Here is what worked for me (although in Visual Studio Professional, not Express, but I guess that should not matter).
Bring up the "Exceptions" Dialog as suggested by Ninjapig.
Click on the Add... Button, to open the "New Exception" dialog.
Select "Common Language Runtime Exceptions" in the drop down box
In the Edit box enter "NUnit.Framework.AssertionException".
Click OK to close the "New Exception" dialog.
Back in the "Exceptions" dialog make sure that both checkboxes (Thrown and User-unhandled) are unchecked.
Now, the debugger should completely ignore a NUnit assertion failure (i.e. a thrown, caught or not, NUnit.Framework.AssertionException).
UPDATE: This will only prevent from breaking into the debugger, it cannot ignore the exception itself; i.e. it will not alter the actual program flow. Appart from changing or replacing or encapsulating the Assert-calls in try-catch blocks, I don't think there is anything that can achieve that (at least not automatically).
I'm uncertain if VS2010 Express has this option, but you can choose the exceptions to break on .
Go to the 'Debug' menu, then select 'Exceptions'
and from here you can select what exceptions to break on
I've ended up referencing nunit-gui-runner.dll and invoking it like
NUnit.Gui.AppEntry.Main(new string[] { Dll });
This brings up the NUnit gui. I can then run the specific test i'm interested in.
I had the same problem. Although your original approach (without the need for a try...catch block) works for most exception types, ArgumentNullException doesn't work. I fixed it like this:
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
bool isArgumentNullExceptionThrown = false;
try
{
new CachedStreamingEnumerable<int>(null);
}
catch (ArgumentNullException)
{
isArgumentNullExceptionThrown = true;
}
Assert.That(isArgumentNullExceptionThrown);
}
It's not as elegant, but it does seem to work.