We're receiving messages on an IBM MQ (using C# and the IBM WebSphere MQ 8.0.0.7 NuGet package).
All the examples we found for receiving messages are simplistic and based on the pattern:
- Receive message
- If no message, throw exception
- Carry on receiving
The principle being the different between "listening" and "receiving".
Given this is a no-frills queue, there is surely a better way to listen to a queue instead of sitting on a loop that is controlled by catching exceptions when there is no queue available in the queue I am "listening"/receiving from.
This is the principle code/pattern:
public void Start(string receiveQueueName)
{
_receiveQueueName = receiveQueueName;
_thread=new Thread(ReceiveText);
_thread.Start();
}
private void ReceiveText()
{
try
{
string responseText = null;
// First define a WebSphere MQ message buffer to receive the message
MQMessage retrievedMessage = new MQMessage();
// Set the get message options
MQGetMessageOptions gmo = new MQGetMessageOptions(); //accept the defaults
//same as MQGMO_DEFAULT
// Set up the options on the queue we want to open
int responseOptions = MQC.MQOO_INPUT_AS_Q_DEF;
using (MQQueue responseQueue =
_mqQueueManager.AccessQueue(receiveQueueName, responseOptions))
{
while (isEnabled)
{
// creating a message object
MQMessage mqMessage = new MQMessage();
try
{
responseQueue.Get(mqMessage);
// ---- DEAL WITH THE MESSAGE ----
mqMessage.ClearMessage();
}
catch (MQException mqe)
{
if (mqe.ReasonCode == 2033)
{
// ----- NO MESSAGE ------
continue;
}
else
{
throw;
}
}
}
// Close the queue
responseQueue.Close();
}
}
catch (MQException mqExOuter)
{
// ----- DEAL WITH THE ERROR -----
}
}
Note that there is additional code here to support the threading, which has been removed for clarity.
I accept this is a "subjective", etc. question but please consider that I am appealing to the expertise of people, which is valid and important for subsequent readers.