WPF, VB , and the Application object - wpf

Scenario:
The VB 6 form has a InteropControl (WinForms).
The InteropControl has a ElementHost
The ElementHost has my WPF control
Everything seems to be working except that Application.Current seems to be null when I need it. All I really want to do is hook into the unhandled exception event before the first form is fully displayed.
In this scenario is a WPF Application object ever created?
If so, when it is created?
If not, what causes messages to be pumped?
What would happen if I started the Application object on a background thread?

First I will explain how message loops work in interop scenarios, then I will answer your questions and give a few recommendations.
Message loop implementations in your scenario
Your scenario involves three separate technologies: VB 6, WinForms, and WPF. Each of these technologies is implemented on top of Win32. Each has its own GetMessage()/DispatchMessage() loop to pump Win32 window messages.
Here is where each GetMessage()/DispatchMessage() loop is implemented:
VB 6 implements it internally
WinForms implements it in System.Windows.Forms.Application
WPF implements it in System.Windows.Threading.Dispatcher
WPF Application object is optional
Your question assumes that WPF implements the message loop in the Application object. This is not the case. In WPF, all essential functions that WinForms handled in the Application object have been moved to other objects such as Dispatcher, HwndSource, InputManager, KeyboardDevice, MouseDevice, etc.
In WPF the Application object is completely optional. You can construct a complete WPF application with a complex UI without ever creating an Application object. An application object is only useful if you need one of the services it provides, for example:
A common ResourceDictionary
Mapping WM_APPACTIVATE message into Activated and Deactivated events
Mapping WM_QUERYENDSESSION message into OnSessionEnding event
Lifecycle management (Startup/Run/Shutdown/Exit)
Automatic shutdown when the last window or main window closes
Default icon for WPF windows
Remembering the first window opened (MainWindow)
Common registration for NavigationService events (Navigated, etc)
StartupUri
The Application class also provides several useful static members such as FindResource, GetResourceStream and LoadComponent that don't require an Application object to exist.
When you call Application.Run(), all it does is:
Install the mechanism to handle WM_APPACTIVATE and WM_QUERYENDSESSION, and
Execute Dispatcher.Run()
All of the actual message loop functionality is in Dispatcher.Run().
Registering for unhandled exceptions in WPF message loop
The Application.DispatcherUnhandledException event you were trying to use is a simple wrapper around the Dispatcher.UnhandledException event. I think they included it in the Application object because WinForms programmers expected it to be there, but your question shows that this may have backfired.
To register for unhandled exceptions from WPF's Dispatcher, all you have to do is:
Dispatcher.Current.UnhandledException += ...;
Unlike Application.Current, Dispatcher.Current cannot be null: If you access Dispatcher.Current from a thread that doesn't yet have a Dispatcher, one will be created automatically.
Once you have subscribed to Dispatcher.UnhandledException, any unhandled exception from a Dispatcher message loop on the current thread will cause your event handler to be called. Note that this only applies to unhandled exceptions when Dispatcher.Run() is pumping messages: When another technology such as VB 6 or WinForms is pumping messages, that technology's exception handling mechanism will be used instead.
WPF message loop also optional
Not only can WPF run without creating an Application object, it can also function without Dispatcher.Run(), as long as another technology is pumping Win32 window messages. This is done by creating a dummy window and/or subclassing a WPF window to install a message hook. Thus no matter what message loop is pumping messages, WPF will work as expected.
In fact, when you use ElementHost, the WPF Dispatcher is not used for message pumping unless you use one of the following methods:
Window.ShowDialog
Dispatcher.Invoke
Dispatcher.Run (or equivalently, Application.Run)
DispatcherOperation.Wait
Because of this, your WPF exception handler will probably not be called. Instead you will need to install your exception handler at the VB 6 or WinForms level.
Answers to your questions
In this scenario is a WPF Application object ever created?
No.
If not, what causes messages to be pumped?
VB 6 is pumping the messages.
What would happen if I started the Application object on a background thread?
Very little:
If you have application resources these would be created on the background thread, possibly leading to exceptions when they are used on the main thread.
If you add a handler to Application.Current.DispatcherUnhandledException it would only apply to the background thread. In other words, the handler will never be called unless you create windows on the background thread.
Your Application.Startup will be called from the background thread, which is probably a bad thing. Ditto for StartupUri.
Recommendation
From what you are asking it sounds like you are getting an unhandled exception during the loading of your WPF control and you want to catch that exception. In this case, the best plan is probably to wrap your WPF control inside a simple ContentControl whose constructor uses code like this to construct the child:
Dispatcher.Current.UnhandledException += handler;
Disptacher.Current.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
{
Content = CreateChildControl();
Dispatcher.Current.Invoke(DispatcherPriority.ApplicationIdle, new Action(() => {});
});
How it works: The BeginInvoke delays construction of the child until VB 6 and/or InteropControl have completed all processing. The Invoke call after the child control is created invokes an empty action at low priority, causing all pending DispatcherOperations to complete.
The net result is that any exceptions that were thrown within or just after the constructor are now passed to your exception handler.

In WPF, the Application object is not directly responsible for the message pump, it is the Dispatcher. When you start a WPF app, Application.Run() is called at startup, which calls Dispatcher.Run().
In your interop scenario, Application.Current will return null since it is never created. Message pumping is handled by VB, since it creates the main window. If you rely on it in your code you can either:
Create a new Application object:
if (Application.Current != null)
{
new Application();
}
Application is a singleton, so it will be automatically stored in Application.Current.
Avoid relying on it whenever possible (which I think is the recommended way). You should note that many of the services this class provides (e.g. the Exit event) will not be available in your scenario anyhow. If all you need is the unhandled exception event, you can use Dispatcher.CurrentDispatcher.UnhandledException.

Related

How to deal with cross-thread access exceptions?

A common exception one can get when working with multiple threads in WPF is:
The calling thread cannot access this object because a different thread owns it
What are the options to deal with this properly?
Depending on the situation there are various options:
Accessing a control from another thread
e.g. updating a TextBlock with progress information.
Data Binding:
In this case the easiest thing you can do is avoiding the direct interaction with the control. You can just bind the property you want to access or modify to an object whose class implements INotifyPropertyChanged and then set the property on that object instead. The framework will handle the rest for you. (In general you rarely should need to interact with UI-elements directly, you can almost always bind the respective properties and work with the binding source instead; one case where direct control access may be necessary is control authoring.)
There are some cases where data binding alone is not enough, for example when trying to modify a bound ObservableCollection<T>, for this you need...
Dispatching:
You can dispatch your accessing code to the thread owning the object, this can be done by calling Invoke or BeginInvoke on the Dispatcher owning the object being accessed (getting this Dispatcher is possible on another thread).
e.g.
new Thread(ThisThreadStart).Start();
void ThisThreadStart()
{
textBlock.Dispatcher.Invoke(new Action(() => textBlock.Text = "Test"));
}
If it is not clear on which thread a method is executed you can use Dispatcher.CheckAccess to either dispatch or execute an action directly.
e.g.
void Update()
{
Action action = () => myTextBlock.Text = "Test";
var dispatcher = myTextBlock.Dispatcher;
if (dispatcher.CheckAccess())
action();
else
dispatcher.Invoke(action);
}
If an object is not a DispatcherObject and you still need the associated Dispatcher you can use Dispatcher.CurrentDispatcher in the thread creating the object (so doing this in the method being executed by a thread will not do you any good). For convenience as you usually create objects on the application's main UI thread; you can get that thread's Dispatcher from anywhere using Application.Current.Dispatcher.
Special cases:
BackgroundWorker
Move any control access to ProgressChanged as it occurs on the thread that created the instance (which should of course be the UI-thread)
Timers
In WPF you can use the DispatcherTimer for convenience, it does the dispatching for you so any code in Tick is invoked on the associated dispatcher. If you can delegate the dispatching to the data binding system you of course can use a normal timer as well.
You can read more about how the Dispatcher queue works and WPF threading in general on MSDN.
Accessing an object created on another thread
e.g. loading an image in the background.
If the object in question is not Freezable you should in general simply avoid creating it on another thread or restricting access to the creating thread. If it is Freezable you just need to call Freeze to make it accessible to other threads.
Accessing a data object from another thread
That is, the type whose instance is being updated is user-code. If an exception is thrown this situation probably came about by someone using DependencyObject as base type for a data class.
This situation is the same as accessing a control and the same approaches can be applied but usually it should be avoided in the first place. Granted, this allows for simple property change notifications via dependency properties and those properties can also be bound but often enough this is just not worth giving up thread-independency. You can get change notifications from INotifyPropertyChanged and the binding system in WPF is inherently asymmetrical, there always is a property that is bound (target) and something that is the source for this binding. Usually the UI is the target and the data is the source, meaning that only UI components should need dependency properties.
That would be several hundred lines of code, for something I "figured out".
But the summary is:
App_OnStartup
generate a background thread
in the callback,
Call
Application.Current.MainWindow.Dispatcher.CheckAccess() - gets the exception
Application.Current.Dispatcher.CheckAccess() does not
I have a udp listener object that communicates through events where the method/callbacks are +='ed in my mainWindow wpf .cs file.
The event handler functions are called with parameters, one being the message I want displayed in a listbox in the mainWindow.cs
Using the information in this thread by H.B. above;
I have added, tested and handled the crossthread in wpf in my eventhandler callback using the following code, but I use a real message not a hard coded one:
listBox1.Dispatcher.Invoke(new Action(() => listBox1.Items.Add("MessageHere")));
UPDATE:
This is better because you can put more things in the anonymous function.
listBox1.Dispatcher.Invoke((Action)delegate
{
listBox1.Items.Add(e.ReaderMessage);
});

C# WM_VScroll & VScroll Control

I am trying to create a subclass of VScroll control and intercepting the WM_VSCROLL message to do some stuff. On msdn, and countless articles/forums, WM_VSCROLL is supposed to be 0x115, even in the windows header file that's what it is. However waiting on 0x115 doesn't bring anything. I realized it's coming through as 0x2115 instead, even this article is using it as 0x2115. Any reason/explanation as to why it's coming as 0x2115 instead? Is it because it's a WinForms control?
Thanks
Yes, this is pretty standard in Windows GUI class libraries, Winforms is no exception. The native Windows control, ScrollBar in your case, send notifications to their parent. After all, they were designed to make their parent act on the notification, not themselves. Or in other words, you expect the parent window to scroll.
That however is not very compatible with the notion of a control class whose behavior you can modify by overriding its message handling and generation. Or for that matter the idea of events in .NET, anybody can subscribe to the Scroll event, not just the parent.
That buys a lot of goodness, but something must be done to get the WM_VSCROLL message from the parent back to the control. Which is what the Winforms plumbing takes care of. It sends the message back but alters the message number to indicate that it was a reflected message, not the original. It adds 0x2000. The value of the (fake) WM_REFLECT message in the Winforms source code.

How do I get the UI thread's Dispatcher?

Is there any way to get the UI thread's Dispatcher when you have no reference to any UI elements?
You can grab the UI Dispatcher from the static application instance: Application.Current.Dispatcher
You may want to check Application.Current for null first, as it can be cleared during a shutdown sequence.
The following works much better for me when being used in a WinForms application that happens to be also using WPF (in my case Esri's Arcmap.exe)
private System.Windows.Threading.Dispatcher Dispatcher { get; set; }
// I put this in my view model constructor as it MUST be called from UI thread
Dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
The other method (which involved calling new System.Windows.Application() to populate System.Windows.Application.Current) caused issues for me every time I opened a new WPF window and then closed it. Not only did this null out System.Windows.Application.Current, but I could no longer open up new windows as their InitializeComponents() methods, all failed with:
System.InvalidOperationException: 'The Application object is being
shut down.'
So far the new solution is working without those side effects.

.NET Compact Framework: how to ensure form is visible before running code?

We've got a Model-View-Presenter setup with our .NET Compact Framework app. A standard CF Form is implementing the view interface, and passed into the constructor of the presenter. the presenter tells the form to show itself by calling view.Run(); the view then does a Show() on itself, and the presenter takes over again, loading up data and populating it into the view.
Problem is that the view does not finishing showing itself before control is returned to the presenter. since the presenter code blocks for a few seconds while loading data, the effect is that the form is not visible for a few seconds. it's not until after the presenter finishes it's data load that the form becomes visible, even though the form called Show() on itself before the presenter started its data loading.
In a standard windows environment, i could use the .Shown event on the form... but compact framework doesn't have this, and I can't find an equivalent.
Does anyone know of an even, a pinvoke, or some other way to get my form to be fully visible before kicking off some code on the presenter? at this point, i'd be ok with the form calling to the presenter and telling the presenter to start it's data load.
FYI - we're trying to avoid multi-threading, to cut down on complexity and resource usage.
The general rule is: never do anything blocking on the UI thread
The UI in Windows (and in Windows CE as well) has an asynchronous nature. Which means that most API calls do not necessarily do whatever they're supposed to do immediately. Instead, they generate a series of events, which are put into the event queue and later retrieved by the event pump, which is, essentially, an infinite loop running on the UI thread, picking events from the queue one by one, and handling them.
From the above, a conclusion can be drawn that if you continue to do something lengthy on the UI thread after requesting a certain action (i.e. showing the window in your case), the event pump cannot proceed with picking events (because you haven't returned control to it), and therefore, your requested action cannot complete.
The general approach is as follows: if you must do complex data transformation/loading/preparing/whatever, do it on a separate thread, and then use Control.BeginInvoke to inject a delegate into the UI thread, and touch the actual UI controls from inside that delegate.
Despite your irrational fear of "complexity" that multithreading brings with it, there is very little to be afraid of. Here's a little example to illustrate the point:
public void ShowUI()
{
theForm = new MyForm();
theForm.Show();
// BeginInvoke() will take a new thread from the thread pool
// and invoke our delegate on that thread
new Action( PrepareData ).BeginInvoke(null,null);
}
public void PrepareData()
{
// Prepare your data, do complex computation, etc.
// Control.BeginInvoke will put our delegate on the UI event queue
// to be retrieved and executed on the UI thread
theForm.BeginInvoke( new Action( PutDataInTheForm ) );
}
public void PutDataInTheForm()
{
theForm.textBox1.Text = "data is ready!";
}
While you may play with alternative solutions, the general idea always remains the same: if you do anything lengthy on the UI thread, your UI will "freeze". It will not even redraw itself as you add new UI elements on the screen, because redrawing is also an asynchronous process.
Therefore, you must do all the complex and long stuff on a separate thread, and only do simple, small, guaranteed to run fast things on the UI thread. There is no other alternative, really.
Hope this helps.
If your key problem is that the form won't paint before your presenter data loading methods are completed, and you have a call to this.Show() in your Form_Load, try putting Application.DoEvents() directly after this.Show() to force/allow the form to paint.
protected void Form_Load(blah blah blah)
{
this.Show();
Application.DoEvents();
... data loading methods ...
}
No need to create another thread if you don't want to (although a couple of seconds have to be dealt with somehow).
You can use the activated event. Because it will fire when the form is activated, you need a boolean local to the form to check wether or not the form has been created for the first time.
Another option for you is to disconnect the event handler right after you finish presenting the form.

What is UserPreferenceChangedEventHandler in C# winform applications?

I found some of my winform application controls, such as DataGridView and ToolStrips, are referred to by UserPreferenceChangedEventHandlers. I have no idea what setting of the controls will generate such references and why such references keep my control alive in memory. How can I remove such references from that event? Thanks.
It is the delegate type for the SystemEvents.UserPreferenceChanged event. This event fires when Windows broadcasts the WM_SETTINGCHANGE message. Which typically happens when the user uses a control panel applet and changes a system setting.
Several controls register an event handler for this event, DataGridView, DateTimePicker, MonthCalendar, ProgressBar, PropertyGrid, RichTextBox, ToolStrip, NumericUpDown. They typically are interested in font or cue changes and anything that would affect the layout.
SystemEvents.UserPreferenceChanged is a static event. Registering a handler and forgetting to unregister it causes a memory leak, it prevents the control from being garbage collected. The listed controls ensure this doesn't happen, they unregister the event handler in either the OnHandleDestroyed() or the Dispose() method.
You'll get in trouble when neither of those two methods run. That will happen when you remove the control from the container's Controls collection and forget to Dispose() it. While forgetting to call Dispose() is not normally a problem, it is a hard requirement for controls. It is easy to forget too, controls are normally automatically disposed by the Form. But that only happens for controls in the Controls collection.
Also be sure to call Dispose() on forms that you display with the ShowDialog() method, after you obtained the dialog results. The using statement is the best way to handle that.
One more excruciating detail is important about the UserPreferenceChanged event, it is often the one that deadlocks your app when you create controls on a worker thread. Typically when the workstation is locked (press Win+L). Which cannot come to a good end when you use the controls I listed, the SystemEvents class tries to raise the event on the UI thread but of course cannot do this correctly when more than one thread has created them.
Also the kind of bug that can have a lasting effect, a splash screen for example can get the SystemEvents class to guess wrong about which thread is your UI thread. After which it then permanently raises the event on the wrong thread. Very ugly to diagnose, the deadlock is well hidden.

Resources