XAML 应用程序调用了为其他线程封送的接口- Windows应用商店应用

iezvtpos  于 2022-12-07  发布在  其他
关注(0)|答案(5)|浏览(105)

所以,首先我读了很多关于这个问题的文章,但我仍然不知道如何解决它。基本上,我尝试与一个WebSocket通信,并将接收到的消息存储在绑定到列表视图的可观察集合中。我知道我从socket正确地得到了响应,但当它试图将其添加到可观察集合时,它给了我以下错误:

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

我读过一些关于“dispatch”的信息,也读过一些其他的东西,但是我感到非常困惑!下面是我的代码:

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

    }

这就是约束力:

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

如何在绑定到listview的可观察集合的同时消 debugging 误?

fhity93d

fhity93d1#

这解决了我的问题:

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

在Windows应用商店应用中获取CoreDispatcher的正确方法

oxcyiej7

oxcyiej72#

尝试替换

messageList.Add(read);

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

如果您是从Window类别外部呼叫,请尝试:

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

q1qsirdb3#

对基于任务的异步方法进行了轻微的修改,但这里的代码不会等待。

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

此代码将等待,并允许您返回一个值:

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;
    }

在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;
    }
jtjikinw

jtjikinw4#

也许这不是一个“好”的做法,但它的工作。。我离开了一个消息从WebSocket,到mainBody示例,在那里我有一个timered阅读器。。

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; 
    }
x8diyxa7

x8diyxa75#

在Xamarin中,我通过使用以下代码解决了这个问题:

Device.BeginInvokeOnMainThread(() => {
   // code goes here
});

相关问题