Getting lock exception when receiving messages from Service Bus in Service bus trigger Azure Function
sonal khatri
51
Reputation points
I prepared this code for receiving messages from service bus queue and sending email via SendGrid.
MessageLockDuration for my message on queue is set to 5 minutes and there is no other receiver except this function but still I am receiving the Error: An unhandled exception occurred in the message batch receive loop. Microsoft.Azure.ServiceBus: The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue, or was received by a different receiver instance. I am not sure what's wrong. Can you help?
public async Task Run([ServiceBusTrigger("%QueueName%", Connection = "ConnectionString")]Message[] messages, MessageReceiver messageReceiver, ILogger log,
[SendGrid(ApiKey = "SendGridAPIKey")] IAsyncCollector<SendGridMessage> messageCollector)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {messages}");
try
{
BlobServiceClient blobServiceClient = new BlobServiceClient(StorageAccountConnectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(ContainerName);
foreach (Message message in messages)
{
CustomerRequest customerRequest = JsonConvert.DeserializeObject<CustomerRequest>(Encoding.UTF8.GetString(message.Body));
var msg = new SendGridMessage();
var memoryStream = new MemoryStream();
if (customerRequest.Type == TypeEnum.Today)
{
BlobClient blobClient = containerClient.GetBlobClient(customerRequest.FirstFileName);
var response = await blobClient.DownloadAsync();
await response.Value.Content.CopyToAsync(memoryStream);
foreach (var recipient in customerRequest.RecipientsDaily)
{
msg.AddTo(recipient);
msg.AddContent("text/html", "See Attached");
msg.SetFrom(new EmailAddress(SendGridSenderAddress));
msg.SetSubject("Subject");
var attachment = new Attachment
{
Filename = customerRequest.FirstFileName,
Content = Convert.ToBase64String(memoryStream.ToArray())
};
msg.AddAttachment(attachment);
await messageCollector.AddAsync(msg);
}
}
else
{
BlobClient blobClient = containerClient.GetBlobClient(customerRequest.SecondFileName);
var response = await blobClient.DownloadAsync();
await response.Value.Content.CopyToAsync(memoryStream);
foreach (var recipient in customerRequest.Recipients)
{
msg.AddTo(recipient);
msg.AddContent("text/html", "See Attached");
msg.SetFrom(new EmailAddress(SendGridSenderAddress));
msg.SetSubject("Subject");
var attachment = new Attachment
{
Filename = customerRequest.SecondFileName,
Content = Convert.ToBase64String(memoryStream.ToArray())
};
msg.AddAttachment(attachment);
await messageCollector.AddAsync(msg);
}
}
await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
}
}
catch(Exception ex)
{
log.LogError($"Error occurred while processing the request {ex}");
}
}
#endregion
}