The application called an interface that was marshalled for a different thread - Windows Store App

C#MultithreadingXamlWindows Store-Apps

C# Problem Overview


So, first I have read a ton of threads on this particular problem and I still do not understand how to fix it. Basically, I am trying to communicate with a websocket and store the message received in an observable collection that is bound to a listview. I know that I am getting a response back properly from the socket, but when it tries to add it to the observable collection it gives me the following error:

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

I've read some information on "dispatch" as well as some other things, but I am just massively confused! Here is my code:

public ObservableCollection<string> messageList  { get; set; }
private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
    {
        string read = "";
        try
        {
            using (DataReader reader = args.GetDataReader())
            {
                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                read = reader.ReadString(reader.UnconsumedBufferLength);
            }
        }
        catch (Exception ex) // For debugging
        {
            WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
            // Add your specific error-handling code here.
        }

        
        if (read != "")
           messageList.Add(read); // this is where I get the error

    }

And this is the binding:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    //await Authenticate();
    Gameboard.DataContext = Game.GameDetails.Singleton;
    lstHighScores.ItemsSource = sendInfo.messageList;
}

How do I make the error go away while still binding to the observable collection for my listview?

C# Solutions


Solution 1 - C#

This solved my issue:

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
    {
        // Your UI update code goes here!
    }
);

https://stackoverflow.com/questions/16477190/correct-way-to-get-the-coredispatcher-in-a-windows-store-app/18485317#18485317

Solution 2 - C#

Try replacing

messageList.Add(read); 

with

Dispatcher.Invoke((Action)(() => messageList.Add(read)));

If you're calling from outside your Window class, try:

Application.Current.Dispatcher.Invoke((Action)(() => messageList.Add(read)));

Solution 3 - C#

Slight modification for task based async methods but the code in here will not be awaited.

await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    // Your UI update code goes here!
}
).AsTask();

This code WILL await, and will allow you to return a value:

    private async static Task<string> GetPin()
    {
        var taskCompletionSource = new TaskCompletionSource<string>();

        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        async () =>
        {
            var pin = await UI.GetPin();
            taskCompletionSource.SetResult(pin);
        }
        );

        return await taskCompletionSource.Task;
    }

And on Android:

    private async Task<string> GetPin()
    {
        var taskCompletionSource = new TaskCompletionSource<string>();

        RunOnUiThread(async () =>
        {
            var pin = await UI.GetPin();
            taskCompletionSource.SetResult(pin);
        });

        return await taskCompletionSource.Task;
    }

Solution 4 - C#

Maby this is not a "good" practice, but it works.. I leave a message from webSocket, to mainBody instance, where I have a timered reader...

public class C_AUTHORIZATION
{
    public Observer3.A_MainPage_cl parentPageInstance; //еще одни экземпляр родителя
    public WebSocket x_Websocket; 
    private string payload = "";
    private DateTime nowMoment = DateTime.Now;
    public void GET_AUTHORIZED()
    {
       bitfinex_Websocket= new WebSocket("wss://*****.com/ws/2");

        var apiKey = "";
        var apiSecret = "";
        DateTime nowMoment = DateTime.Now;            

        payload = "{}";            

        x_Websocket.Opened += new EventHandler(websocket_Opened);                                                         
       x_Websocket.Closed += new EventHandler(websocket_Closed);  
    }
    
    void websocket_Opened(object sender, EventArgs e)
    {
        x_Websocket.Send(payload);
        parentPageInstance.F_messager(payload);
    }
    
    void websocket_Closed(object sender, EventArgs e)
    {
        parentPageInstance.F_messager("L106 websocket_Closed!");
        GET_AUTHORIZED();  
    }
   

}

public sealed partial class A_MainPage_cl : Page
{      
    DispatcherTimer ChartsRedrawerTimer;
    public bool HeartBeat = true;
   
    private string Message;        
    public A_MainPage_cl()
    {
       this.InitializeComponent();
      
        ChartsRedrawerTimer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 100) }; 
        ChartsRedrawerTimer.Tick += Messager_Timer;
        ChartsRedrawerTimer.Start();

        
    }        
         
    private void Messager_Timer(object sender, object e)
    {            
        if(Message !=null) // 
        {
            F_WriteLine(Message);
            Message = null; //  

        } 
    }
    public void F_messager(string message) // 
    { 
        Message = message; 
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYecatsView Question on Stackoverflow
Solution 1 - C#variousView Answer on Stackoverflow
Solution 2 - C#BaldrickView Answer on Stackoverflow
Solution 3 - C#Christian FindlayView Answer on Stackoverflow
Solution 4 - C#Pavel ArhipovView Answer on Stackoverflow