从另一个线程更新 Blazor 中的项目列表
Update list of items in Blazor from another thread
我正在尝试获取一个项目列表,以便在从消息队列收到消息时进行更新。
这似乎只在每 其他 次收到消息时起作用。它肯定每次都在 SubscribeAsync
调用中调用匿名方法,我不明白为什么它不是每次都更新。我假设它与在不同线程中的匿名方法有关。知道我做错了什么吗?
@page "/"
@inject IMessageQueueHelperFactory MessageQueueHelperFactory
@inject ILogger<Index> Logger
@using Microsoft.Extensions.Logging
@using Newtonsoft.Json
<ul class="list-group">
@foreach (var user in Users) {
<li class="list-group-item">@user</li>
}
</ul>
@code
{
private List<string> Users { get; set; } = new List<string>();
protected override void OnInitialized()
{
MessageQueueHelperFactory.Create(Queues.UserRegistration)
.SubscribeAsync(async x =>
{
var user = JsonConvert.DeserializeObject<UserRegistrationData>(x);
Users.Add(user.Username);
await InvokeAsync(StateHasChanged);
});
base.OnInitialized();
}
}
从微软的文档中,我看到了这篇文章:
Component initialization methods
上面写着:
Blazor Server apps that prerender their content call OnInitializedAsync twice
Once when the component is initially rendered statically as part of
the page.
A second time when the browser establishes a connection back to the
server.
所以,我想如果您使用 OnAfterRenderAsync 并将第一个参数设置为 true 将解决您的问题
我正在尝试获取一个项目列表,以便在从消息队列收到消息时进行更新。
这似乎只在每 其他 次收到消息时起作用。它肯定每次都在 SubscribeAsync
调用中调用匿名方法,我不明白为什么它不是每次都更新。我假设它与在不同线程中的匿名方法有关。知道我做错了什么吗?
@page "/"
@inject IMessageQueueHelperFactory MessageQueueHelperFactory
@inject ILogger<Index> Logger
@using Microsoft.Extensions.Logging
@using Newtonsoft.Json
<ul class="list-group">
@foreach (var user in Users) {
<li class="list-group-item">@user</li>
}
</ul>
@code
{
private List<string> Users { get; set; } = new List<string>();
protected override void OnInitialized()
{
MessageQueueHelperFactory.Create(Queues.UserRegistration)
.SubscribeAsync(async x =>
{
var user = JsonConvert.DeserializeObject<UserRegistrationData>(x);
Users.Add(user.Username);
await InvokeAsync(StateHasChanged);
});
base.OnInitialized();
}
}
从微软的文档中,我看到了这篇文章: Component initialization methods
上面写着:
Blazor Server apps that prerender their content call OnInitializedAsync twice
Once when the component is initially rendered statically as part of the page.
A second time when the browser establishes a connection back to the server.
所以,我想如果您使用 OnAfterRenderAsync 并将第一个参数设置为 true 将解决您的问题