【发布时间】:2019-08-08 19:58:23
【问题描述】:
在我的 Asp.Net Core 应用程序中,我通过 SignalR Core 从 .Net 客户端接收更新。通过这些更新,我尝试了解在 .Net 客户端上运行的后台服务的状态。 一些例子:
“定时器已成功启动。”
“定时器已成功暂停。”
“定时器已成功恢复。”
“定时器无法启动。”
我想在我的 Asp.Net Core 应用程序中使用这些消息,并通过从 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");
}
}
在上面的代码示例中,您可以看到我要完成的工作。我遇到的问题是在集线器之外的类中无法访问该事件,因此我无法使用它。
【问题讨论】:
-
不使用 SignalR 直接从后台服务执行相同操作有什么问题?
-
计时器将在 Azure 云上运行 4 小时。我读到后台服务可能会在一段时间后自动停止,所以我正在尝试编写一个可以在 Azure 应用服务中自行运行的 WebJob。
标签: asp.net-core signalr.client asp.net-core-signalr