Corrado's Blog 2.0

Online thoughts of a technology funatic

UWP Share target and COM Exception 0×80004002

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.

No Responses to “UWP Share target and COM Exception 0×80004002”

RSS feed for comments on this post. TrackBack URL

Leave a Response