UNIVPLMDataIntegration/Admin.NET/Admin.NET.Core/Ai/Services/SSE/BaseSseChannelManager.cs
2025-06-18 02:10:24 +08:00

54 lines
1.4 KiB
C#

using System.Threading.Channels;
using Admin.NET.Core.Ai.Interface;
namespace Admin.NET.Core.Ai.Services.SSE;
/// <summary>
/// SSE通道管理
/// </summary>
public class BaseSseChannelManager : ISseChannelManager
{
private readonly ConcurrentDictionary<long, Channel<string>> _userChannels = new();
/// <summary>
/// 注册
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public ChannelReader<string> Register(long userId)
{
var channel = Channel.CreateBounded<string>(new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.Wait
});
_userChannels[userId] = channel;
return channel.Reader;
}
/// <summary>
/// 注销
/// </summary>
/// <param name="userId"></param>
public void Unregister(long userId)
{
if (_userChannels.TryRemove(userId, out var channel))
{
channel.Writer.TryComplete(); // 结束读端
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="userId"></param>
/// <param name="message"></param>
/// <param name="cancellationToken"></param>
public async Task SendMessageAsync(long userId, string message, CancellationToken cancellationToken = default)
{
if (_userChannels.TryGetValue(userId, out var channel))
{
await channel.Writer.WriteAsync(message, cancellationToken);
}
}
}