[英]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
.发生这种情况是因为在使用
ObservableCollection
时Add()
必须在 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.