0
votes
public static async Task DoMessage()
    {
        const int numberOfMessages = 10;

        queueClient = new QueueClient(ConnectionString, QueueName);

        await SendMessageAsync(numberOfMessages);

        await queueClient.CloseAsync();
    }

    private static async Task SendMessageAsync(int numOfMessages)
    {
        try 
        { 
            for (var i = 0; i < numOfMessages; i++)
            {
                var messageBody = $"Message {i}";
                var message = new Message(Encoding.UTF8.GetBytes(messageBody));
                message.SessionId = i.ToString();
                await queueClient.SendAsync(message);
            }


        }
        catch (Exception e)
        {

        }
    }

This is my sample code to send message to the service bus queue with session id.

My question is if I call DoMessage function 2 times: Let's name it as MessageSet1 and MessageSet2, respectively. Will the MessageSet2 be received and processed by the received azure function who dealing with the receiving ends of the message.

I want to handle in order like MessageSet1 then the MessageSet2 and never handle with MessageSet2 unless MessageSet1 finished.

1

1 Answers

0
votes

There are a couple of issues with what you're doing.

First, Azure Functions do not currently support sessions. There's an issue for that you can track.

Second, the sessions you're creating are off. A session should be applied on a set of messages using the same SessionId. Meaning your for loop should be assigning the same SessionId to all the messages in the set. Something like this:

private static async Task SendMessageAsync(int numOfMessages, string sessionID)
{
    try 
    { 
        var tasks = new List<Task>();
        for (var i = 0; i < numOfMessages; i++)
        {
            var messageBody = $"Message {i}";
            var message = new Message(Encoding.UTF8.GetBytes(messageBody));
            message.SessionId = sessionId;
            tasks.Add(queueClient.SendAsync(message));
        }
        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
    catch (Exception e)
    {
       // handle exception
    }
}

For ordered messages using Sessions, see documentation here.