AppDomain.UnhandeledException event not fired - wpf

In a WPF application, the app simply crashes, without the above event being fired.
(I'm also registered to DispatcherUnhandeledException, which doesn't fire as well.)
I conclude that it doesn't fire since the handler is defined to place a log entry. When looking at the log, there's no corresponding entry.
It happens in a production environment; I'm unable to point at a particular scenario.
I've read few descriptions on scenarios where this might happen, but I still don't have a clear grasp on this. Can anyone share his experience / knowledge on this?
How can I find the root of the crash and solve it?
Many thanks.

Common causes for this would be a StackOverflowException or an OutOfMemoryException. To find the cause you could attach the Visual Studio Debugger and enable all Exceptions in the Exceptions window. You will then be prompted when any exception occurs in your application.

Related

What causes VisualTreeHelper::HitTest to return incomplete results, and sometimes no results?

I had a scenario where I was connecting to a Windows WPF app, through a network connection to drive UI for the purposes of test automation.
Sometimes my requests to the UI using VisualTreeHelper returned no results regardless of the apparent state of the logical or visual trees.
This, more than a question is the documentation of the solution to the problem.
It turns out that I was detecting the network connection availability and IMMEDIATELY after it responded, I issued calls that exercised VisualTreeHelper and catching the UI while being rendered. The result of that call was incomplete and subsequent calls failed completely (no elements were found ever).
My practical solution was to delay for 2 seconds between when the communication was open, and the first call to VisualTreeHelper. That eliminated the weird state caused by calling UI too soon. I tested with 100 iterations of the app rebooting with no problems.
I 'Googled' the problem but didn't find good results.
Interestingly, I asked ChatGPT about it and it informed me:
"If you try to access elements of the visual tree before they have been fully rendered, you may get unexpected results, or an exception may be thrown."
I asked the bot to tell me what sources it had for the assertion and the only link I got:
"here's a link to the Microsoft documentation that mentions the risk of calling VisualTreeHelper before the visual tree is fully rendered:
https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.visualtreehelper.getchild?view=netcore-3.1#remarks"
Unfortunately such link actually doesn't mention anything like that. This may be due to ChatGPT using 2021 data, and the link content has changed.
A friend suggested I used archive.log (an Internet archive) to see if a previous version of such link had the desired information, but none was found.
ChatGPT provided relevant information, but could not provide sources where it distilled it from.
Lastly, I acknoledge that the 'ideal' way to address the problem of racing to use VisualTreeHelper before the UI is done rendering is to wait for an event the main window calls:
private void MainWindow_Loaded(object sender, RoutedEventArgs e);
and gate any use of VisualTreeHelper until this event is raised.
My approach is not stricktly the ideal, but practical with little effort. The 2 second delay does not significantly impact my scenario.
After I delayed 2 seconds before using VisualTreeHelper to wait for UI to render, I had no problems.
The short answer is (as you have observed) that they're not there yet when you try finding the controls.
The visual tree that the visual tree helper works with is the object graph of UI controls etc which are within a window.
A window is a content control.
When you instantiate a window, the window itself is created using the constructor.
I'm not sure there's a point where there can be just the window itself in the visual tree but this is conceptually how it works.
Parent windows is first then the root panel content and the content of that root.
The "tree" of controls is window > content panel > child controls.
Constructing a window can take a while. 2 seconds seems kind of slow but developers are prone to putting all sorts of things in constructors. The time taken may vary depending on how much code the developer has put in there, connectivity speeds etc etc.
That variance would explain why a test result will vary.
The correct event to handle for a window would be contentrendered. As the name suggests, this fires after all the content of the window has been rendered.
With a usercontrol or page you can handle loaded but you're best deferring processing via use of dispatcher. Loaded doesn't guarantee everything is rendered.

WPF Temporary Display Freeze

I have a standalone WPF application running on .NET 3.5. Every so often, the display simply freezes up for several seconds. This is most noticeable on screens where something is being updated often. Here is a video showing the problem.
While the display is frozen, the interface remains responsive (video).
I've come across some other posts with similar problems who attributed it to a SW/HW rendering issue. To be safe, I disabled HW rendering altogether, but still have the problem.
I ran a file monitor during the freezes to see if there is some extraordinary file access or activity going on, but nothing is out of the ordinary.
Final note: The target platform is a small touch-screen panel PC without much memory or horsepower (512 MB). I only see this issue on the target, never on my development PC, which has much more in the way of resources.
UPDATE
I thought I had fixed the issue by removing some animation code, but it did not work. I am still encountering the problem and I'm at the end of my rope.
Here's some more things I've tried:
Upgraded to .NET 4.0. Same behavior.
Added debug code to all methods that may be invoked via DispatcherTimer (which are called on the UI thread) to make sure none of them are holding up the UI.
I'm really stumped here and have added a bounty. As I mentioned, the problem only occurs on the target PC (link).
I tend to suspect either .NET GC or the OS swapfile when this kind of behavior shows up.
For the former, you could try the .NET performance counters to monitor for suspect activity.
If the device has a swap file, you can disable it and see if the behavior changes.
As others have said, a profiler (or some what of isolating what condition is inducing the delay - even just attaching and breaking the debugger when it occurs) would be a good way to get more information.
Did you tried to profile the application on the tested system? Using a memory and/or performance profiler?
You could get some good informations out of this type of test : some .Net profilers
And here's one for WPF : WPF profiler from microsoft
The culprit was the following method call:
new HwndSource(new HwndSourceParameters());
This was added to my application because it patched a memory leak problem in .NET 3.5. This work-around can be found here. If I remove this call, the rendering issues go away.
I took out the call and fixed the memory leak in another way (removing storyboard animation and using code behind instead)

Visual Studio 2008 ContextSwitchDeadlock with log4net and NHibernate

I'm facing an extremely weird bug here and I'm not really sure If I'm following the right path to solving it or even how to solve it.
Here is the problem I'm facing: I start debugging a WPF application which uses log4net, NHibernate and LINQ to NHibernate, and when I try to get an Entity from the database my application and sometimes VS hang for a lot of time, and after a while an exception dialog opens showing a message containing the following information on a ContextSwitchDeadlock MDA:
The CLR has been unable to transition from COM context 0x34fc1a0 to COM context 0x34fc258 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this
I copied the code files to a new project and deleted the old project to see If I could make this message disappear, thinking it had something to do with my configuration. I started adding few things at a time to see what was causing it, and when I included log4net configuration code the bug appeared again. First I included it through AssemblyInfo and later trough code configuration on application startup, and absolutely nothing changed at all :(
So, here are my findings:
It only happens when I'm using log4net.
It happens when NHibernate loads an Entity from database (lazy loading).
I don't know what might be the source of this bug. It only happens when debugging in Visual Studio. I've tried following the steps on the "Enabling and Disabling MDAs" section of the following page: http://msdn.microsoft.com/en-us/library/d21c150d.aspx, but that doesn't work either, VS still hangs and it's memory usage increases.
When I run the program normally none of this happens, so I'm pretty sure this is not a deadlock situation, as this question suggests: contextswitchdeadlock (I've also tried the solutions posted there).
Because of that, I've decided to disable log4net and enable it again when deploying my app.
I'm posting this question to find out if somebody else has faced this bug or if somebody has some suggestions on how to solve it. Finally, it might help somebody else facing this very same problem.
When using the DebugAppender all the entities in the databases are loaded and all its data written to the debug output. That was causing the ContextSwitchDeadlock MDA since it tookmore than 60 seconds to run.
Disabling the DebugAppender solved my problem.
Thanks to Mauricio Scheffer for the tip.

Where should exceptions be caught and handled in a WPF application?

We have exception catching code in most of our event handlers etc, this leads to very complex logic, with flags that are set to say if there has been an exception so as not do the next step etc.
At first sight I would move all exception report/logging to the AppDomain.UnhandledException event, however from my experience with WinForms this will lead to a lot of exceptions being lost.
Also when there is an exception we have include details of the operation the user was trying to do in the log message.
So what are people experiences both bad and good at exception logging/reporting/recovering in WCF applications?
(I would love to say that we had something like the Model-View ViewModel (MVVM) pattern) in use, but we don’t and are a long way from being able to use any “clean” design like that)
Its not specific to WPF, but the best place to handle exceptions is to handle them at the point where user interaction with the form is converted into a logic process. This is either in the codebehind or in a controller method.
Only at this level do you know what the user is trying to do and what reasonable steps to take when an exceptional situation is encountered.
Of course, if you don't know what exceptions may be thrown don't try to handle them. And don't bother handling exceptions that you can't do anything about.
You should never have to use flags to say exceptions have been handled - that smells like bad design.
Exceptions fall into two categories:
expected (e.g. validation failed, data could not be put into database)
unexpected
your expected ones should be handled pretty quickly, and logged depending on the type of exception. For instance, if the user entered some data that was rejected by validation code in the business layer, i would catch the exception and notify the user, but not log it - because it was expected and i can deal with it. Others could be "expected", but you cannot deal with it - like a WCF call failed due to timeout or oversized data packet. This you should definately log - you may even be able to recover from it, so once again it should be caught and dealt with. Note the lack of flags - an exception is either dealt with, or it continues to bubble up. If you need to take an action you can do so, and then rethrow the exception to let it bubble up further - look, still no flags :)
Another approach i have taken in the past when throwing (custom) expected exceptions in an ASP.NET application is to mark it as being capable of being handled locally or not. This means that when the aspx caught the error (generic error handler in a base page that all apsx's inherited from), then it knew whether it should just show it locally within the page (after doing a text lookup in a resource file), or whether it should redirect to an error page. This approach was especially useful when doing a mixture of standard postbacks and ajax callbacks (may not be particularly useful to WPF apps though).
For major unexpected errors, you can catch those at the Application level, here is a previous SO post about it. Another two related posts that might be useful here, and here.
Another thing i should mention is to make sure your error logging is relatively bulletproof - there is nothing worse than your exception logging process throwing an exception, and losing all the valuable details of that tricky bug you are trying to track down for that irate user.

Am I a discoverer of a bug in the WPF engine?

We have a MFC 8 application compiled with /CLR that contains a larger amount of Windows Forms UserControls which again contain WPF user controls using ElementHost. Due to the architecture of our software we can not use HwndHost directly. We observed an extremely strange behavior here that we can not make any sense of:
When the CPU load is very high during startup of the application and there are a lot live of ElementHost instances, the whole property engine completely stops working. For example animations that usually just work fine now never update the values of the bound properties, they just stay at some random value after startup. When I set a property that is not bound to anything the value is correctly stored in the dependency property (calling the getter returns the new value) but the visual representation never reflects that. I set the background to red but the background color does not change.
We tested this on a lot of different machines all running Windows XP SP2 and it is pretty reproducible.
The funny thing here is, that there is in fact one situation where the bound properties actually pickup a new value from the animation and the visual gets updated based on the property values. It is when I resize the ElementHost or when I hide and reshow the parent native control. As soon as I do this, properties that are bound to an animation pickup a new value and the visuals rerender based on the new property values - but just once - if I want to see another update I have to resize the ElementHost.
Do you have any explanation of what could be happening here or how I could approach this problem to find it out? What can I do to debug this? Is there a way I can get more information about what WPF actually does or where WPF might have crashed? To me it currently seems like a bug in WPF itself since it only happens at high CPU load at startup.
I don't do any work with those techs, so I can't really speak to that. However, to me it sounds like some kind of deadlock is occurring in your code which is blocking calls to redraw() (or its equivalent). Resizing the window will force a redraw, but your normal mechanism for telling it to redraw when you've changed something might be blocked.
Is it possible you have a race condition in your code somewhere? On a lightly-loaded system things might happen in the correct order, but on the heavily loaded one the timing might be different. Perhaps that's triggering a deadlock in your code?
If you can attach a debugger, take a look at the threads that are running. If you can see what each thread is waiting on and what else it holds locks on (You can do this with Java, not sure about your app) that might help you determine where it's dying.
There is no detail on how you load your data on startup... If you haven't done it yet, consider using Dispatcher.BeginInvoke (with a priority lower than render) or a BackgroundWorker
Here is a post on how to do this!
PS. Just be careful if your objects that you bind to is an ObservableCollection<>... Read more about the issues I had doing this here
Most of the time, select isn't broken (as the saying goes).
It does sound very much like some kind of race or deadlock as #Herms suggests.
You could of course check MSDN for known bugs. Depending on what your code is like, when I'm really stuck with a bug I find that removing chunks of code until you're left with a minimal test case usually helps.
Nothing strange happens in your application. Dependency system "stops working" because of the fact, that UI thread, all the system relies to is busy. It's all about priorities for different Disparcher objects. I can consider you to use background processes doe for prolong operations, while all synchronization done in UI thread.
Also, you can play with task prioritization (DispatcherPriority enum as first parameter of Invoke/BeginInvoke methods)
Another tip, can help you is to implement DoEvent pattern, known from WinForms (to process messages in windows queue)
To summarize, you should remember, that you're working in STA. Also, when you're using ElementHost in Windows XP, you actually remove hardware acceleration. Try to use .NET 3.5 SP1 to fix it somehow, but still you have to leave CPU for rendering and dispatching things.

Resources