most likely the web service is exiting, which sets the cancellation token. how is the app hosted? IIS express, app or IIS? are you getting any unhandled errors that exits the app?
Why is my BackgroundService getting cancelled?

I have a simple BackgroundService.
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
NotifyBase? notification = null;
try
{
notification = await _queue.PullAsync(stoppingToken);
Where PullAsync is:
public class NotificationQueue : INotificationQueue
{
private readonly Channel<NotifyBase> _queue;
public NotificationQueue()
{
var opts = new BoundedChannelOptions(256) { FullMode = BoundedChannelFullMode.Wait };
_queue = Channel.CreateBounded<NotifyBase>(opts);
}
/// <inheritdoc />
public ValueTask<NotifyBase> PullAsync(CancellationToken cancellationToken)
{
return _queue.Reader.ReadAsync(cancellationToken);
}
If I leave my web app alone, running under the Visual Studio debugger, then after about 10 minutes it throws a cancellation exception: CancelledException Message: The operation was canceled. With a call stack of:
at System.Threading.Channels.AsyncOperation`1.GetResult(Int16 token)
at LouisHowe.web.Services.BackgroundWorker.NotificationBackgroundService.<ExecuteAsync>d__5.MoveNext() in C:\Git\LouisHowe\LouisHowe.web\Services\BackgroundWorker\NotificationBackgroundService.cs:line 32
What is going on here? I've read this post but while it talks about how to handle a cancel, it says nothing about why one would be triggered. I'm not cancelling it so I'm guessing the Visual Studio web server is. But why?
I want to keep this running for the life of the app server. But each time it gets a notification
from the queue, it processes that fast. But the BackgroundService
remains running, waiting for another entry in the queue, for the lifetime of the app service.
And please don't suggest an Azure Function. That is not a good solution here as it takes time to spin up/down and these notifications come in randomly.
thanks - dave
Developer technologies | ASP.NET | ASP.NET Core
-
Bruce (SqlWork.com) 78,311 Reputation points Volunteer Moderator
2024-02-18T21:08:58.87+00:00