events - Blazor:从服务发送到组件的事件为空
问题描述
我有由 Blazor 组件和 Worker Service 组成的程序。我正在使用 .NET CORE 3.1
我的代码基于Blazor 组件的手册
在我的工人服务方面,我有:
public event Func<double, Task> Notify;
public double Data{ get; set; }
public async Task Update(double data)
{
if (Notify != null)
{
await Notify.Invoke(data).ConfigureAwait(false);
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Update(Data).ConfigureAwait(false);
...
await Task.Delay(1000, stoppingToken).ConfigureAwait(false);
}
}
在我的 Blazor 组件中:
@using MyNamespace
@inject WorkerService MyService
@implements IDisposable
<div>@DataToDisplay</div>
@code {
private double DataToDisplay{ get; set; }
protected override void OnInitialized()
{
MyService.Notify += OnNotify;
}
public async Task OnNotify(double data)
{
await InvokeAsync(() =>
{
DataToDisplay= data;
StateHasChanged();
});
}
public void Dispose()
{
MyService.Notify -= OnNotify;
}
}
调试后我通知,Notify 事件在 Blazor 组件中正确连接,在 OnInitialized() 方法中(我也尝试过带有 的版本OnInitializedAsync()
)但是,每次,当服务调用Update()
方法时,在条件检查期间:if (Notify != null)
,Notify 为 null .
我找不到原因。感谢您的任何建议!
解决方案
public class InjectableService
{
public double Value { get; set; }
public event Func<Task> Notify;
public double Data { get; set; }
public async Task RefreshAsync(double value)
{
if (Notify is { })
{
Value = value;
await Notify.Invoke();
}
}
public class MyService : BackgroundService
{
private readonly InjectableService _injectableService;
public MyService(InjectableService injectableService)
{
_injectableService = injectableService;
}
public async Task Update(double value)
{
await _injectableService.RefreshAsync(value);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Update(_injectableService.Value + 0.1).ConfigureAwait(false);
await Task.Delay(1000).ConfigureAwait(false);
}
}
}
@inject InjectableService MyService
@implements IDisposable
<p>@MyService.Value</p>
@code {
protected override void OnInitialized()
{
MyService.Notify += OnNotify;
}
public async Task OnNotify()
{
await InvokeAsync(() =>
{
StateHasChanged();
});
}
public void Dispose()
{
MyService.Notify -= OnNotify;
}
}
在 Startup.cs 中:
services.AddHostedService<MyService>();
services.AddSingleton<InjectableService>();
推荐阅读
- json - Nifi Jolt Transform Spec - 重命名值
- c# - 队列空值返回并抛出 NullReferenceException
- java - 为什么我不能通过 apktool 获取源代码?
- javascript - Cypress-compare file contents with an array always return false
- embedded - STM32F030F4P6 仅在从闪存启动时运行中断处理程序。从引导加载程序启动时重置
- verilog - 无故障状态机输出
- java - Javafx 网格窗格中心元素
- java - Java中集合的子类
- c++ - 乘以双打,其中没有一个等于零给我零
- css - 添加第 8 个列表项时,仅使用 CSS 更改其他列表元素的属性