C# Send(): Get message size before sending to RabbitMQ

I have an application that sends some message to a RabbitMQ application and I am having a problem with some limitations regarding the message size sent to RabbitMQ.

The erros states that:

message size 203760127 is larger than configured max size 134217728

That said, I cannot edit the max size on RabbitMQ side, so this is out of question.
The message is structured as following:

Message
    int UserID
    string UserToken
    string datetime
    List<T> Itens

Where each object in Itens has information regarding an specific item.
There are a few moments where a lot of itens are modified at once and because of that, the message gets larger than the limit of 134217728 bytes.

I can get a loop creating a new message with only one item and send it, thus avoiding going above the limit. However as result it can take a while to be processed on the other side.

So I was thinking of finding a way to get the size of the current message and the objects in the list. So I can, if nedded, separating it efficiently.

For example: Suppose that my list has 100 itens, and I found that the limit of itens I can send to RabbitMQ without causing the error is 30. Then I would send 3 messages with 30 itens and one with 10 itens, on total of 4 messages.

Something like:

int MAX_SIZE = 130000000; // safety margin to avoid going above maximum limit (134217728 bytes);
MessageToSend = OriginalMessage;
MessageToSend.Itens = new List<T>();
foreach(T item in MessageToSend.Itens)
{
    MessageToSend.Itens.add(item);
    if(sizeOf(MessageToSend) >= MAX_SIZE) // Each time the size of the message gets equal or above the limit, send it and reset the list;
    {
        await sendEndpoint.Send<Message>(MessageToSend);
        MessageToSend.Itens = new List<T>();
    }
}

await sendEndpoint.Send<Message>(MessageToSend); // Send whats is left;

Any clues?

Read more here: Source link