Search code examples
c#windows-phone-8windows-runtimewindows-phone-8.1windows-phone

Windows Phone Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)


My Windows Runtime Application reads a NDEF NFC-Tag. When the App reads the NFC-Tag correct my method message receivedwill open.

private void messageReceived(ProximityDevice sender, ProximityMessage message)
{
    device.StopSubscribingForMessage(NFCID);
    var ndefMessage = NdefMessage.FromByteArray(message.Data.ToArray());

    StringBuilder sb = new StringBuilder();
    foreach (NdefRecord record in ndefMessage) sb.AppendLine(Encoding.UTF8.GetString(record.Payload, 0, record.Payload.Length));

    String data= sb.ToString();
    ShowData(data);
} 

private void ShowData(string data)
{
    tbx.Text = data;
}

When I want to set this data to a textfield, every time a exception is thrown: Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)


Solution

  • You need to dispatch it first:

    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                tbx.Text = data;
            });
    

    EDIT: Obviously this is not always the best solution. Do it this way instead if you still receive that error: Run code on UI thread in WinRT