I have a function that checks if there is still a message in my servicebus which it constantly checks.
The function that gets the ammount is:
public int GetActiveMessageCount()
{
var connectionString = azureConnectionStringWithoutEntityPath;
long messageCount = 0;
try
{
var nameSpaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
messageCount = nameSpaceManager.GetQueue(azureQueueName).MessageCountDetails.ActiveMessageCount;
}
catch
{
throw;
}
return (int)messageCount;
}
And the check is:
public bool MessageCountBiggerThenZero()
{
int messageCount = 0;
try
{
messageCount = this.GetActiveMessageCount();
}
catch (Exception e)
{
Debug.WriteLine("An error occured while checking if the messageValue is bigger then zero and not null saying : " + e);
}
return messageCount > 0;
}
this works perfectly in the beginning when there are zero messages but after it starts receiving messages and then passes the last messsage it still passes the MessageCountBiggerThenZero check.
Does anyone know how this can be? Does the serviceBus return other values after it's last message?
Edit:
More insight into the check (So it still passes the if statement even if there is no message anymore):
public object RecieveOneMessageFromServiceBus()
{
var client = QueueClient.CreateFromConnectionString(azureConnectionString);
BrokeredMessage brokermessage = null;
client.PrefetchCount = 1; // get 1 message at a time
if (MessageCountBiggerThenZero())
{
try
{
// try to recieve message
}
catch
{
throw;
}
}
else
{
return null;
}
}
Ok I seem to have fixed it but I have no clue how and why. I did implement it as Bruce says but this did not work. Maybe the complete method was not send fast enough or something else is going one but now I changed my receiving method to receive and delete and added a timer for getting the message of about 5 seconds like:
var client = QueueClient.CreateFromConnectionString(azureConnectionString,ReceiveMode.ReceiveAndDelete);
brokermessage = client.Receive(TimeSpan.FromSeconds(5));
With this code it seems to work and anyone able to explain me why would be very much wanted.
Edit:
See comment below for extra explanation on how to implement this better