简体   繁体   English

将项目添加到 ObservableCollection 时出现 InteropServices.COMException

[英]InteropServices.COMException when adding item to ObservableCollection

I using signal R core to send me a list of messages but this happen我使用信号 R 核心向我发送消息列表,但发生了这种情况

public ObservableCollection<ChatMessage> Messages { get; set; } = new ObservableCollection<ChatMessage>();

public async void InitSignalRAsync()
    {
        ChatMessage mess = new ChatMessage();
        hubConnection = new HubConnectionBuilder().WithUrl("http://localhost:5000/chatHub").Build();
        await hubConnection.StartAsync();
        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            mess.user = user;
            mess.message = message;
            Messages.Add(mess);
        });
    }

I got an error我有一个错误

System.Runtime.InteropServices.COMException: System.Runtime.InteropServices.COMException:

at my在我

Messages.Add(mess); Messages.Add(混乱);

when I receive the data当我收到数据时

As Martin noted , you must update ViewModel components from their UI thread.正如Martin 指出的,您必须从它们的 UI 线程更新 ViewModel 组件。

However, for a solution, I recommend using the more general-purpose SynchronizationContext rather than the UWP-specific Dispatcher class.但是,对于解决方案,我建议使用更通用的SynchronizationContext而不是 UWP 特定的Dispatcher类。 By using the more general type, your code is more reusable and more testable.通过使用更通用的类型,您的代码更可重用且更易于测试。

Eg:例如:

public ObservableCollection<ChatMessage> Messages { get; set; } = new ObservableCollection<ChatMessage>();

public async Task InitSignalRAsync()
{
  var context = SynchronizationContext.Current;
  hubConnection = new HubConnectionBuilder().WithUrl("http://localhost:5000/chatHub").Build();
  await hubConnection.StartAsync();
  hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
  {
    var mess = new ChatMessage
    {
      user = user,
      message = message,
    };
    context.Post(_ => Messages.Add(mess));
  });
}

I also changed your async void to async Task (again, better reusability and testability), and made a new ChatMessage for each chat message, which I believe is the intended behavior.我还将您的async void更改async Task (再次,更好的可重用性和可测试性),并为每个聊天消息ChatMessage了一个新的ChatMessage ,我认为这是预期的行为。

This is happening because the Add() must run on the UI thread when you are using ObservableCollection .发生这种情况是因为在使用ObservableCollectionAdd()必须在 UI 线程上运行。 So to make it work, make sure to execute the call in Dispatcher.RunAsync() :因此,要使其工作,请确保在Dispatcher.RunAsync()执行调用:

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { 
    Messages.Add(mess);
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 InteropServices.COMException - InteropServices.COMException C# AutoIt InteropServices.COMException 错误 - C# AutoIt InteropServices.COMException error System.Runtime.InteropServices.COMException 将元素添加到 ObservableCollection 时<string> - System.Runtime.InteropServices.COMException while adding an element to ObservableCollection<string> 从ASP MVC控制器运行Word时保持获取InteropServices.COMException - Keep Getting InteropServices.COMException when running Word from ASP MVC Controller 为什么我在尝试从 C# 启动 QTP 时收到 InteropServices.COMException? - Why do I get an InteropServices.COMException when attempting to launch QTP from C#? 间歇性的“ InteropServices.COMException / ForwardCallToInvokeMember”在范围单元格上访问Value2 - Intermittent “InteropServices.COMException / ForwardCallToInvokeMember” accessing Value2 on Range cell com 异常 excel InteropServices.COMException - c# - com exception excel InteropServices.COMException - c# 如何在不安装Excel的情况下修复InteropServices.COMException? - How can I fix InteropServices.COMException without installing Excel? 为什么使用此代码会得到“ InteropServices.COMException / ForwardCallToInvokeMember”? - Why would I get, “InteropServices.COMException / ForwardCallToInvokeMember” with this code? 更改 ObservableCollection 时 Xamarin.Forms UWP (Windows) 应用程序中的 System.Runtime.InteropServices.COMException - System.Runtime.InteropServices.COMException in Xamarin.Forms UWP (Windows) App when changing ObservableCollection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM