David Thielen
David Thielen

Reputation: 32976

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

line 32 is notification = await _queue.PullAsync(stoppingToken);

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?

Upvotes: 1

Views: 99

Answers (0)

Related Questions