Asp.net core 是否有办法在SignalR Core Hub中实现事件?
在我的Asp.Net Core应用程序中,我通过SignalR Core从.Net客户端接收更新。通过这些更新,我试图了解在.Net客户端上运行的后台服务的状态。 一些例子:Asp.net core 是否有办法在SignalR Core Hub中实现事件?,asp.net-core,signalr.client,asp.net-core-signalr,Asp.net Core,Signalr.client,Asp.net Core Signalr,在我的Asp.Net Core应用程序中,我通过SignalR Core从.Net客户端接收更新。通过这些更新,我试图了解在.Net客户端上运行的后台服务的状态。 一些例子: “计时器已成功启动。” “计时器已成功暂停。” “计时器已成功恢复。” “无法启动计时器。” 我想在Asp.Net核心应用程序中使用这些消息,并通过从中心(数据访问层)发送事件将它们传输到项目的上层(逻辑层)。 我似乎不知道怎么做,也没有找到任何关于这个问题的文档 public class TimerHub : Hub
- “计时器已成功启动。”
- “计时器已成功暂停。”
- “计时器已成功恢复。”
- “无法启动计时器。”
public class TimerHub : Hub
{
public event EventHandler TimerCouldNotBeStarted;
// Method called by .Net Client
Task TimerStatusUpdate(string message)
{
switch (message)
{
case "Timer could not be started.":
OnTimerCouldNotBeStarted(EventArgs.Empty); // Raise event
break;
}
return Clients.All.SendAsync("EditionStatusUpdate", message);
}
protected virtual void OnTimerCouldNotBeStarted(EventArgs e)
{
TimerCouldNotBeStarted?.Invoke(this, e);
}
}
public class EditionEngine
{
private readonly IHubContext<TimerHub> _timerHubContext;
public EditionEngine(IHubContext<TimerHub> hubContext)
{
_timerHubContext = hubContext;
_timerHubContext.TimerCouldNotBeStarted += TimerNotStarted; // Event is not found in the TimerHub
}
private static void TimerNotStarted(object sender, EventArgs e)
{
Console.WriteLine("Event was raised by Hub");
}
}
公共类TimerHub:Hub
{
公共事件事件处理程序TimerCulldnotBestArted;
//.Net客户端调用的方法
任务计时器状态更新(字符串消息)
{
开关(信息)
{
案例“计时器无法启动”。:
OnTimerCouldNotBeStarted(EventArgs.Empty);//引发事件
打破
}
返回Clients.All.SendAsync(“EditionStatusUpdate”,消息);
}
受保护的虚拟void OnTimerCouldNotBeStarted(EventArgs e)
{
TimerCouldNotBeStarted?调用(this,e);
}
}
公共类编辑引擎
{
私有只读IHubContext _timerHubContext;
公共编辑引擎(IHubContext-hubContext)
{
_timerHubContext=hubContext;
_timerHubContext.TimerCouldNotBeStarted+=TimerNotStarted;//在TimerHub中找不到事件
}
私有静态void TimerNotStarted(对象发送方,事件参数e)
{
Console.WriteLine(“事件由Hub引发”);
}
}
在上面的代码示例中,您可以看到我试图实现的目标。我遇到的问题是,该事件在集线器之外的类中不可访问,因此我无法使用它。将您的
时间更改为您在DI中提供的服务。然后在Hubs构造函数中解析服务,并在方法中使用它
public class TimerHub : Hub
{
private readonly TimeService _timer;
public TimerHub(TimerService timer)
{
_timer = timer;
}
Task TimerStatusUpdate(string message)
{
switch (message)
{
case "Timer could not be started.":
_timer.OnTimerCouldNotBeStarted(EventArgs.Empty); // Raise event
break;
}
return Clients.All.SendAsync("EditionStatusUpdate", message);
}
}
不使用信号器直接从后台服务执行相同操作有什么不对?计时器将在Azure云上运行4小时。我读到后台服务可能会在一段时间后自动停止,所以我正在尝试编写一个WebJob,它可以在Azure应用程序服务中自行运行。