question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] ServiceBusProcessorProcessor StopProcessingAsync freezes

See original GitHub issue

Hi,

Im trying to stop processor in some processing conditions, but it freezes for some reason and never comeback to continuation. I just made a small sample and simple code to reproduce this behaviour, its not my actual application (Added comment // #### IT FREEZES HERE ####).

        static async Task Main(string[] args)
        {
            var client = new ServiceBusClient(_connectionString);

            var options = new ServiceBusProcessorOptions
            {
                AutoCompleteMessages = false
            };

            var processor = client.CreateProcessor(_topicName, _topicName, options);

            async Task MessageHandlerAsync(ProcessMessageEventArgs args)
            {
                Console.WriteLine($"Processing: {args.Message.Body}");
             
                if (args.Message.Body.ToString() == "2")
                {
                    Console.WriteLine("Processor Stopping...");

                   // ####   IT FREEZES HERE   ####
                    await processor.StopProcessingAsync().ConfigureAwait(false);

                    Console.WriteLine("Processor Stopped");
                }

                new ManualResetEvent(false).WaitOne((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

                await args.CompleteMessageAsync(args.Message).ConfigureAwait(false);
            }

            async Task ErrorHandlerAsync(ProcessErrorEventArgs args)
            {
                await Task.CompletedTask;
            }

            processor.ProcessMessageAsync += MessageHandlerAsync;
            processor.ProcessErrorAsync += ErrorHandlerAsync;

            await processor.StartProcessingAsync(_tokenSource.Token).ConfigureAwait(false);

            _ = Task.Run(async () =>
            {
                var topicClient = new TopicClient(_connectionString, _topicName);

                var messages = new List<Message>();

                for (int i = 0; i < 5; i++)
                {
                    messages.Add(new Message
                    {
                        Body = Encoding.UTF8.GetBytes(i.ToString())
                    });
                }

                await topicClient.SendAsync(messages).ConfigureAwait(false);
            });

            Console.ReadKey();
        }
    }

I runned it on debug with sdk code included in my project and noticed it freezes here:

        public virtual async Task StopProcessingAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
            bool releaseGuard = false;
            try
            {
                await _processingStartStopSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                releaseGuard = true;

                if (ActiveReceiveTask != null)
                {
                    Logger.StopProcessingStart(Identifier);
                    cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();

                    // Cancel the current running task.

                    RunningTaskTokenSource.Cancel();
                    RunningTaskTokenSource.Dispose();
                    RunningTaskTokenSource = null;

                    // Now that a cancellation request has been issued, wait for the running task to finish.  In case something
                    // unexpected happened and it stopped working midway, this is the moment we expect to catch an exception.
                    try
                    {
                        // ####   IT FREEZES HERE   ####
                        await ActiveReceiveTask.ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        // Nothing to do here.  These exceptions are expected.
                    }

                    ActiveReceiveTask.Dispose();
                    ActiveReceiveTask = null;
                }
            }
            catch (Exception exception)
            {
                Logger.StopProcessingException(Identifier, exception.ToString());
                throw;
            }
            finally
            {
                if (releaseGuard)
                {
                    _processingStartStopSemaphore.Release();
                }
            }
            Logger.StopProcessingComplete(Identifier);
        }
  • Tried Azure.Messaging.ServiceBus 7.2.1, 7.2.1 and 7.3.0-beta-1
  • Windows 10 .NET Core 5
  • Visual Studio 16.9.4

Thanks in Advance

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
danielmarbachcommented, Aug 19, 2021

Or if more control is needed maybe manually fetching with a receiver is better suited for the scenario. But difficult to say without knowing more. And yes the beauty of the processor is that it waits until handlers are done

0reactions
thiagorizzocommented, Aug 31, 2021

Thanks for the answers. Now, i’m triggering it through fire-and-forget.

Read more comments on GitHub >

github_iconTop Results From Across the Web

[BUG] Stopping ServiceBusProcessor causes some ...
Once processor is stopped/disposed it lefts often some messages locked in the queue. It seems caused by TaskCanceledException thrown in AmqpReceiver.
Read more >
ServiceBusProcessor.StopProcessingAsync ...
Signals the processor to stop processing messaging. Should this method be called while the processor is not running, no action is taken.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found