【问题标题】:Is there a way to implement events in SignalR Core Hub?有没有办法在 SignalR Core Hub 中实现事件?
【发布时间】: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


【解决方案1】:

将您的 TimerCouldNotBeStarted 事件更改为您放入 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多