Manage queues by using the C# SDK

更新时间:
复制 MD 格式

Use the C# SDK to create a queue, send a message, receive and delete a message, and delete the queue in Simple Message Queue (formerly MNS).

Before you begin

Before you begin, ensure that you have:

  • An Alibaba Cloud account or RAM user with the required permissions

  • An AccessKey pair (AccessKey ID and AccessKey secret). To create one, go to the AccessKey Management page or the RAM console

  • The regional SMQ endpoint for your queue. Endpoints vary by region. To find your endpoint, go to the SMQ console and click View the endpoints of a queue. For more information, see View the endpoints of a queue

Set up the SDK

  1. Download the latest version of the SDK for C# and decompress the package.

  2. Add the decompressed folder to Visual Studio as a solution. The solution contains four projects.

  3. Right-click the AliyunSDK_MNS project and select Rebuild. This generates the Aliyun.MNS.dll file in the bin directory.

    Note

    Add a reference to Aliyun.MNS.dll in any project that calls the SMQ SDK.

  4. Open the SyncTopicSample.cs file in the AliyunSDK_MNS_Sample project.

  5. Set the following properties in Visual Studio:

    • Set AliyunSDK_MNS_Sample as the startup project.

    • Set SyncTopicSample as the startup object.

  6. At the top of SyncTopicSample.cs, specify your AccessKey ID, AccessKey secret, and endpoint.

Create a queue

Create a queue with custom parameters. The default queue name in the sample code is myqueue.

// Configure queue parameters. For a full list, see Queue in the API reference.
var createQueueRequest = new CreateQueueRequest
{
    QueueName = _queueName,
    Attributes =
    {
        VisibilityTimeout = 30,          // Seconds a received message stays invisible. Default: 30.
        MaximumMessageSize = 40960,      // Maximum message size in bytes.
        MessageRetentionPeriod = 345600, // Seconds a message is retained. Default: 345600 (4 days).
        PollingWaitSeconds = 30          // Long polling timeout in seconds. Maximum: 30.
    }
};

try
{
    var queue = client.CreateQueue(createQueueRequest);
    Console.WriteLine("Create queue successfully, queue name: {0}", queue.QueueName);
}
catch (MNSException me)
{
    // Common causes: network error, queue name already exists.
    Console.WriteLine("CreateQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create queue failed, exception info: " + ex.Message);
}

To create a queue with default parameters, call client.CreateQueue(_queueName) directly.

Send a message

After the queue is created, send a message to it:

try
{
    // Get a reference to the queue.
    var nativeQueue = client.GetNativeQueue(_queueName);

    // Build a send request with a message body.
    var sendMessageRequest = new SendMessageRequest("Alibaba<MessageBody>Cloud");

    // Send the message.
    var sendMessageResponse = nativeQueue.SendMessage(sendMessageRequest);
    Console.WriteLine("Send message succeed");
}
catch (MNSException me)
{
    Console.WriteLine("SendMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Send message failed, exception info: " + ex.Message);
}

To send a plain-text message without extra parameters, call nativeQueue.SendMessage("MessageBody").

Receive and delete a message

Receive a message

Call ReceiveMessage to pull a message from the queue. Pass a WaitSeconds value to enable long polling. The request holds until a message arrives or the timeout expires. You must specify the NextVisibleTime parameter in SMQ. For more information about NextVisibleTime and other message attributes, see QueueMessage.

try
{
    // Long poll for up to 30 seconds.
    var receiveMessageResponse = nativeQueue.ReceiveMessage(30);

    // Save the receipt handle for later deletion.
    // The receipt handle is valid for the duration of VisibilityTimeout.
    _receiptHandle = message.ReceiptHandle;
}
catch (MNSException me)
{
    Console.WriteLine("ReceiveMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("ReceiveMessage failed, exception info: " + ex.Message);
}

Long polling: When WaitSeconds is a non-zero value (maximum 30), the request waits until a message becomes available or the timeout elapses. This reduces empty-response polling and lowers costs.

Visibility timeout: After a client receives a message, the message enters the Inactive state for the duration of VisibilityTimeout. During this window, no other client can receive the same message. When the timeout expires, the message returns to the Active state and becomes available to other consumers. This prevents message loss if a consumer exits unexpectedly.

Delete a message

After you process a message, delete it from the queue by using the receipt handle. Delete the message before the receipt handle expires; otherwise the handle becomes invalid.

try
{
    var deleteMessageResponse = nativeQueue.DeleteMessage(_receiptHandle);
}
catch (MNSException me)
{
    // A MessageNotExist error means the receipt handle has expired.
    // To avoid this, set VisibilityTimeout to a value that gives your
    // application enough time to process the message, or call
    // changeMessageVisibility() to extend it.
    Console.WriteLine("DeleteMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete message failed, exception info: " + ex.Message);
}
Tip: If message processing takes longer than the default visibility timeout, call changeMessageVisibility() to extend the timeout before the receipt handle expires.

Delete a queue

When a queue is no longer needed, delete it to release resources:

try
{
    var deleteQueueResponse = client.DeleteQueue(deleteQueueRequest);
}
catch (MNSException me)
{
    Console.WriteLine("DeleteQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete queue failed, exception info: " + ex.Message);
}