我有一个 .NETBackgroundService
用于使用 .NET 管理通知BlockingCollection<Notification>
。
我的实现是导致 CPU 使用率高,即使BlockingCollection
.
我收集了一些转储,似乎我遇到了线程池饥饿。
我不确定应该如何重构以避免这种情况。
private readonly BlockingCollection<Notification> _notifications;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Task.Run(async () =>
{
await _notificationsContext.Database.MigrateAsync(stoppingToken);
while (!stoppingToken.IsCancellationRequested)
{
foreach (var notification in _notifications.GetConsumingEnumerable(stoppingToken))
{
// process notification
}
}
}, stoppingToken);
}
我也尝试删除 while 循环,但问题仍然存在。
编辑:添加了制作人
public abstract class CommandHandlerBase
{
private readonly BlockingCollection<Notification> _notifications;
public CommandHandlerBase(BlockingCollection<Notification> notifications)
{
_notifications = notifications;
}
protected void EnqueueNotification(AlertImapact alertImapact,
AlertUrgency alertUrgency,
AlertSeverity alertServerity,
string accountName,
string summary,
string details,
bool isEnabled,
Exception exception,
CancellationToken cancellationToken = default)
{
var notification = new Notification(accountName, summary, details, DateTime.UtcNow, exception.GetType().ToString())
{
Imapact = alertImapact,
Urgency = alertUrgency,
Severity = alertServerity,
IsSilenced = !isEnabled,
};
_notifications.Add(notification, cancellationToken);
}
}