Search code examples
azureservicebusazure-servicebus-queues

Subscribe to Queue for a set length of time


I am using .Net Core 2.1 and I have a Web Api project that subscribes to a queue using a MessageReceiver.

What I want is for this subscriber to stay "alive" for x minutes. Now I must admit that I actually thought that the Timeout actually worked this way but I don't think that is the case. This is what I have so far

     var reciever = new MessageReceiver(connectionString, queueName);
     Message message = await reciever.ReceiveAsync(TimeSpan.FromMinutes(2));

     if (message != null)
     { 
          // process
     }

So this is what I am expecting, any messages that hit the queue while this piece of code is running, will be processed.

What I am seeing is that it seems to wait for the timeout to expire before "reading" the message from the queue. Maybe I have misunderstood how the subscriber should work, but what I would like is for the subscriber to just subscribe to the queue for the timeout time.

Any help would be appreciated.


Solution

  • ReceiveAsync(waitTime) is a one time receive until one of the following conditions is fullfilled:

    1. There are messages to be recieved
    2. waitTime has elapsed

    If you want to tie receive operation to a certain period of time, you would either have a loop / message pump for the duration you're interested in that receives message. Or, you could register a message handler in order not to build your own message pump. The drawback of the second option is that to stop receiving you'd need to close the receiving client. Where with the first option, you don't need to close it therefore keeping connection alive.

    Potential solution closed connection would be crating your client with ServiceBusConnection rather than a connection string. That way, when a client is closed, connection is still kept alive.