我有三节课:
当我们在监听类型A时,客户端没有收到任何事件,但是当我们监听类型B或C时,我接收到一半的事件。我想要的是监听抽象类型A,以获取任何扩展它的事件,同时保持强类型。
我无法确定这是否是Signalr的限制,或者我在实现中缺少某些内容。
using Microsoft.AspNetCore.SignalR;
using SignlR.Shared;
using System.Threading.Tasks;
namespace SignlR.Experiments.Hubs
{
public class PolyHub : Hub
{
// Empty
}
public class PolyService
{
private readonly IHubContext<PolyHub> _hubContext;
public PolyService(IHubContext<PolyHub> hubContext)
{
_hubContext = hubContext;
Task.Run(Job);
}
private async Task Job()
{
A example = null;
while (true)
{
example = new B();
await _hubContext.Clients.All.SendAsync("Example", example);
await Task.Delay(250);
example = new C();
await _hubContext.Clients.All.SendAsync("Example", example);
}
}
}
}
using Microsoft.AspNetCore.SignalR.Client;
using SignlR.Shared;
using System;
using System.Threading.Tasks;
namespace SignlR.Consoles
{
class Program
{
static void Main(string[] args)
{
var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44384/poly")
.Build();
connection.StartAsync().Wait();
connection.On<A>("Example", (obj) =>
{
Console.WriteLine("Event" + obj.GetType().FullName);
});
Task.Run(async () =>
{
while (true)
{
await Task.Delay(2000);
Console.WriteLine(connection.State.ToString());
}
});
Console.ReadKey();
}
}
}