UWP Share target and COM Exception 0x80004002

Corrado Cavalli
Corrado Cavalli
Published in
2 min readMar 20, 2018

Goal was very simple initially: Implement a share target inside a UWP application that, when activated, just adds a new entry inside a pre-populated ObservableCollection.
Sound easy right? It doesn’t, and I spent the entire morning fighting against this exception

image

Let’s see how I solved it.
Download Share Source and Target solution from here I won’t go into code detail because if you need to learn how implement both share source and target you can find a detailed description from Microsoft documentation here:

-Share Source
-Share Target

Let’s dig into critical part of the code:

What shared target does is to load an item into an observable collection:

and this is the code that gets invoked when share operation is invoked

In line 9 we add a new item into shared observable collection and the code fails with an InvalidCastException.
I’m used that when those crazy exception raise most of the times they come from threading issues, in fact share operation is invoked on a secondary thread so my next take has been to marshal the operation this way:

but in this case the dispatched action it doesn’t even get invoked, probably because the main message pump is blocked, nice…

So I tried another way, using Windows.Current’s dispatcher

and in this case action is invoked, but… same error

Sad smile

probably because the dispatcher is the same as the one used to create the main application window.
I was totally lost now since, while I’ve found many other developers struggling with this, no one posted a working solution (and this lead to the reason of this post) but, don’t know how, I remembered that there’s another way to access a dispatcher and is via CoreApplication class

And… YES, It works!

Smile

I honestly don’t know what happens behind the scenes, but frankly, didn’t expected this apparently easy task to turn into a semi nightmare, but glad, with some luck honestly, I won over it.

--

--

Corrado Cavalli
Corrado Cavalli

Senior Sofware Engineer at Microsoft, former Xamarin/Microsoft MVP mad about technology. MTB & Ski mountaineering addicted.