MSDN. NB: this is API v2
- Queue messages can be strings (to 64k) or byte[]
- You can add timeSpans to project them into the future
- To dequeue, yet GetMessage, then DeleteMessage within a default of 30 seconds.
- NB: not to be confused with Azure Service Bus Queues - that's a WCF queue.
Sample code
using System;
using System.Configuration;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
namespace MartinWeb.Cloud
{
public class QueueStore
{
private readonly string _queueName;
public QueueStore(string queueName = "queue")
{
_queueName = queueName;
}
private CloudQueue FindQueue()
{
var connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
if (string.IsNullOrEmpty(connectionString))
{
connectionString =
ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString;
}
var storageAccount = CloudStorageAccount.Parse(connectionString);
var queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
var queue = queueClient.GetQueueReference(_queueName);
queue.CreateIfNotExists();
return queue;
}
//a message can be a byte[] or string
public void Add(string message)
{
var cqm = new CloudQueueMessage(message);
var queue = FindQueue();
queue.AddMessage(cqm);
}
public void Add(byte[] message)
{
var cqm = new CloudQueueMessage(message);
var queue = FindQueue();
queue.AddMessage(cqm);
}
public string DeQueue()
{
var queue = FindQueue();
var cqm = queue.GetMessage();
//get then delete. After get, it is invisible for 30 seconds
queue.DeleteMessage(cqm);
return cqm.AsString; //or AsBytes
}
public void BatchDeQueue(int count, Action<string> action)
{
var queue = FindQueue();
//get x messages and make invisible for 5 minutes
var messages = queue.GetMessages(count, TimeSpan.FromMinutes(5));
foreach (var message in messages )
{
action(message.AsString); //process it
queue.DeleteMessage(message); //delete it
}
//if not completed in 5 minutes, the remaining messages become visible again
}
public string Peek()
{
var queue = FindQueue();
var cqm = queue.PeekMessage();
return cqm.AsString; //or AsBytes
}
public int MessageCount()
{
var queue = FindQueue();
//make client get attributes
queue.FetchAttributes();
return queue.ApproximateMessageCount.GetValueOrDefault();
}
}
}