Inserting Messages - Understanding Queue Storage - Part Two

To insert a message into an existing queue, first create a new CloudQueueMessage. Next, call the AddMessage method. A CloudQueueMessage can be created from either a string or a byte array.

A newly added message in a queue will be having a lifespan of 7 days by default, i.e. if no system on the back-end comes and processes that message within 7 days, it'll just get purged from the queue. And also, in case you are having multiple queue listeners on the backend and one system pulls out the message to process it, it will be invisible to all other queue listeners for a particular duration of time called Visibility timeout which is 30 seconds by default.

Step 1

Open your project in Visual Studio and in the Program.cs, add the following code to your Main method just after the code for getting the queue reference. (You may delete the code for creating a queue).

  1. TimeSpan expTime = new TimeSpan(24, 0, 0);  
  2. CloudQueueMessage message = new CloudQueueMessage("Task 2");  
  3. queue.AddMessage(message, expTime, null, null);  
  4. Console.WriteLine("Message Inserted");  

Azure
 
Step 2

Click on Start to run the program and we can see the inserted message without an error that makes sure that the message has been inserted.
 
Azure 

You can verify the same by opening the Tasks queue from the portal. The message of the value Task 1 is listed with an expiration time of 7 days.

Azure 

Step 3

Now, let’s see how you customize the expiration time as your own. Here, I am going to set the expiration time to one day, that is, 24 hours. To do so, you can replace the code with the following where we are setting the value by not going with the default.

  1. TimeSpan expTime = new TimeSpan(24, 0, 0);  
  2. CloudQueueMessage message = new CloudQueueMessage("Task 2");  
  3. queue.AddMessage(message, expTime, null, null);  
  4. Console.WriteLine("Message Inserted");  

Azure 

Step 4

Run the program to insert your new message and on successful running, check the portal. You will see that the new message is added to the queue with a one-day lifespan.
Azure
Azure


Similar Articles