I have this issue. I have a SocketIO server and a Windows store app that sends data to the server, but when I receive something from the server and I try to update the UI, I got this error: If I not update the UI, and send back a message, it works, the problem appears when I touch the UI elements.
An exception of type 'System.Exception' occurred in LiftMeApp Prototype.exe but was not handled in user code
Additional information: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
Here is my code:
socket.On("hi", (data) =>
{
this.LayoutRoot.Children.Add(new TextBlock()
{
Text = "a button"
});
});
I would appreciate any hint or help you may give! Thanks. (Hope someone else had this issue fixed)
In all .NET code (this includes WinForms, WPF, and yes, Windows Store); operations that affect the UI must take place on the UI thread. Your socket is spooling up a read thread (which is why it doesn't block the UI as it waits for data) so your UI changes need to be marshalled to the UI thread.
This is typically accomplished using Dispatcher.BeginInvoke
:
Dispatcher.BeginInvoke(new Action(() =>
{
//Code for UI
}), null);
For windows phone, you need to use (from @Johan Falk source: https://stackoverflow.com/a/23607262/1783619):
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { });
In your case, you would probably be better served by using MVVM and having an items control with a button item template. You could then just add to the bound collection, which will marshal the change onto the UI thread for you, and create the button.
The code ends up a lot nicer that way as well :)
User contributions licensed under CC BY-SA 3.0