ASP.NET Core 3.1-从托管服务中,检查是否已加载客户端(索引)页面 [英] ASP.NET Core 3.1 - From a Hosted Service, check if client (Index) page is loaded

查看:55
本文介绍了ASP.NET Core 3.1-从托管服务中,检查是否已加载客户端(索引)页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用VS2019 Razor Pages模板的简单的1页Web应用程序.托管服务将通过SignalR将数据发送到页面.是否可以检查客户端页面(索引页面)是否已加载,因为如果没有加载,则托管服务将暂停发送数据?当从VS2019运行时,该页面当然会自动打开,但是从"dotnet run"运行.我需要知道用户是否已将页面加载到浏览器中,例如他们可能会在服务启动后将其关闭.

I have a simple 1-page web app using the VS2019 Razor Pages template. The hosted service will send data to the page via SignalR. Is it possible to check if the client page (Index page) is loaded because if not then the hosted service will pause sending data? When running from VS2019 the page of course opens automatically but running from "dotnet run" I need to know if the user has loaded the page into the browser e.g. they might shut it down after the service has started.

namespace TestProject
{
    public class TestService : IHostedService
    {
        public TestService(ILogger<TestService> logger)
        {
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            // HERE - check if index page is loaded - how??

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

    }
}

推荐答案

实现简单的SignalR连接计数器

Implement simple SignalR connection counter

public class SignalRConnectionList
{
    private readonly object _sync = new object();
    private readonly List<string> _items = new List<string>();

    public void Remove(string connectionId)
    {
        lock (_sync)
        {
            _items.Remove(connectionId);
        }
    }

    public void Add(string connectionId)
    {
        lock (_sync)
        {
            _items.Add(connectionId);
        }
    }

    public int Count
    {
        get
        {
            lock (_sync)
            {
                return _items.Count;
            }
        }
    }
}

在Startup类的ConfigureServices中,将SignalRConnectionList添加为单例

In ConfigureServices of Startup class add SignalRConnectionList as singleton

services.AddSingleton<SignalRConnectionList>();

在Hub类中重写OnConnectedAsync和OnDisconnectedAsync方法

Override OnConnectedAsync and OnDisconnectedAsync methods in Hub class

public class ChatHub: Hub
{
    public ChatHub(SignalRConnectionList connectionList)
    {
        ConnectionList = connectionList;
    }

    private SignalRConnectionList ConnectionList { get; }

    public override Task OnConnectedAsync()
    {
        ConnectionList.Add(Context.ConnectionId);
        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception exception)
    {
        ConnectionList.Remove(Context.ConnectionId);
        return base.OnDisconnectedAsync(exception);
    }

现在在IHostedService中,您可以使用上面实现的连接计数器

Now in IHostedService you can use connection counter implemented above

public class SimpleService : BackgroundService
{
    public SimpleService(
        ILogger<SimpleService> logger,
        IHubContext<ChatHub> hubContext,
        SignalRConnectionList connectionList)
    {
        Logger = logger;
        HubContext = hubContext;
        ConnectionList = connectionList;
    }

    private SignalRConnectionList ConnectionList { get; }

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            await Task.Delay(1000, cancellationToken);
            if (ConnectionList.Count > 0)
            {
                await HubContext.Clients.All.SendAsync("ReceiveMessage", "system", "ping " + DateTime.Now, cancellationToken);
            }
        }
    }

这篇关于ASP.NET Core 3.1-从托管服务中,检查是否已加载客户端(索引)页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆