I am learning SignalR and need your help. In the following code, you can see one of the hubs of my first project. In this hub, I create a Queue and fill it using the JoinQueue method. Now I am looking for a technique to print the number of members in the Queue on the console every 5 seconds. I need a way to manage queue outside this hub I guess.
using BackEnd.Model;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace BackEnd.Hubs
{
public class QueueHub : Hub
{
private Queue<QueueItem> userQueue = new Queue<QueueItem>();
public async Task JoinQueue(string userToken)
{
QueueItem user = new QueueItem
{
UserToken = userToken,
ConnectionString = Context.ConnectionId
};
userQueue.Enqueue(user);
Console.WriteLine(userQueue.Count);
}
public override Task OnConnectedAsync()
{
string connectionId = Context.ConnectionId;
Console.WriteLine($"{connectionId} is Connected to the server");
return base.OnConnectedAsync();
}
}
Using Background Service, it can help you implement this requirement.
Here is the test result in my side.
The structure of my test project.
QueueMonitorService.cs
QueueHub.cs
IQueueManager.cs
QueueItem.cs
QueueManager.cs
The last step, we need to register it in the Program.cs file.