1

I have a simple recursive method that calls itself while retrieving messages form an Azure Service Bus Queue. The method adds the messages to a List of messages and then, when there are no more messages in the queue, it sends the List back to it's parent method to be processed.

Under normal circumstances, when all is running well, the queue will never have more that a couple messages in it, as we are constantly pulling messages from the queue just as fast as they arrive. But in theory, if our processor goes down, the messages could stack up in a hurry, and the number of messages could become massive.

I'd like to put an artificial limit on the number of messages that will be pulled out of the queue and put into the List before we gracefully abort the process, send back a batch of messages to be processed, and then keep going again. But I'm not sure of the best way to do this. I could create an integer and add to it each call, checking it's value, and then kick out of the process when it reaches a certain point. But, is there a better way?

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • 2
    It couldn't be any simpler than passing an incrementing integer... – Glen Thomas Mar 28 '16 at 15:27
  • ok. Just wondered if there was some obscure built in C# .NET attribute that counted recursion depths which I could tap into. – Casey Crookston Mar 28 '16 at 15:28
  • 1
    Are you sure recursion is appropriate for the task? – Steve Wellens Mar 28 '16 at 15:31
  • 1
    There are always multiple ways to get a job done, but this one is working well for us. – Casey Crookston Mar 28 '16 at 15:33
  • 2
    You don't even need to add an integer argument to count recursion depth if you just check the size of the List you are accessing to add a particular item. Once the List.Count is > MAX_QUEUE stop your recursion just like you would with the integer argument – nvuono Mar 28 '16 at 15:35
  • You could set up the integer count parameter with a default. That way you don't need to supply the value, but the recursive calls could modify the count for each successive call. – Jeff Mercado Mar 28 '16 at 15:38
  • If you want to do it by manually checking the stack trace, you can see my answer in here: https://stackoverflow.com/questions/5999177/for-c-sharp-logging-how-do-i-obtain-the-call-stack-depth-with-minimal-overhead/65249424#answer-65249424 – donatasj87 Dec 11 '20 at 10:17

1 Answers1

1

Just use the size of the list as the limiter - you don't even need an integer count, because your data structure that you're processing items from is already keeping track of one for you:

if (myMessageList.Length < maxAllowedValue) {
  // execute your getter procedure which includes
  // a call to self()...
}

For this particular problem, you might want to consider using a ConcurrentQueue instead of a List, since that will allow Length to safely change while your recursive data-structure-filling method is working.

TheHans255
  • 2,059
  • 1
  • 19
  • 36