我正在尝试在 Web api 中使用 SignalR 实现数据库更改通知。下面是 NotificationService.cs 的代码
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Npgsql;
using webapi.DBCalls;
using webapi.Models;
namespace webapi.Notification
{
public class NotificationService : IHostedService
{
private IHubContext<HubConfig> _hub;
private readonly ModelAppSettings _appSettings;
private DBInterceptor _db_interceptor;
public NotificationService(IHubContext<HubConfig> hub, IOptions<ModelAppSettings> appSettings)
{
_appSettings = appSettings.Value;
_db_interceptor = new DBInterceptor(_appSettings);
_hub = hub;
}
public Task StartAsync(CancellationToken stoppingToken)
{
onDataTableChangeListener();
return Task.CompletedTask;
}
public void onDataTableChangeListener()
{
using (var connection = new NpgsqlConnection(_appSettings.ConnectionString))
{
connection.Open();
connection.Notification += (o, e) => notifyDataChange(e.Payload);
using (var cmd = new NpgsqlCommand("LISTEN datachange", connection))
cmd.ExecuteNonQuery();
while (true)
connection.Wait();
}
}
public void notifyDataChange(string payload)
{
//DO some work here
}
public Task StopAsync(CancellationToken stoppingToken)
{
return Task.CompletedTask;
}
}
}
我在下面的ConfigurationService AS 下
的 Startup.cs 中注册此服务services.AddHostedService<NotificationService>();
当我运行程序时,它永远不会启动并挂在下面的行。
while (true)
connection.Wait();
我知道我需要重写这个方法,但不知道怎么写。任何帮助,将不胜感激。