I am very new to C# and Azure IoT. Perhaps the problem I have is very simple to solve. I would like to update the an UI Element by invoking a method from the cloud. But I am getting the following Error:
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
I know t has something to do with the fact that the UI is running in another thread. but I didnĀ“t find any solution.
Here the code
public sealed partial class MainPage : Page
{
DeviceClient deviceClient;
public MainPage()
{
this.InitializeComponent();
deviceClient = DeviceClient.CreateFromConnectionString(GlobalConstant.DEVICE_CONNECTION_STRING, TransportType.Mqtt);
deviceClient.SetMethodHandlerAsync("UpdateTextfield", UpdateTextfield, null);
}
private void updateTextField ()
{
IncomingMessage.Text = "Update";
}
private Task<MethodResponse> UpdateTextfield(MethodRequest methodRequest, object userContext)
{
updateTextField();
string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}";
return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
}
}
The process that you are calling the:
IncomingMessage.Text = "Update";
is happening on a thread that is non-UI threads. You need to marshal the thread from the current executing thread to the UI thread.
Windows.UI.Core.CoreDispatcher can be used to this. Here is an example:
using Windows.ApplicationModel.Core;
private async void updateTextField ()
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ()=>{
IncomingMessage.Text = "Update";
});
}
Cross reference: "Run code on UI thread in WinRT"
User contributions licensed under CC BY-SA 3.0