我正在使用 NET Core 5.0.0 开发 API Web ASP.NET Core 项目,我正在使用 Azure.Storage.Queues 12.6.0 来写入和读取队列消息。
一切正常,但我想知道我阅读消息的方式是否正常,或者在速度和效率方面有更好的方法。
这是我正在使用的代码。它只是来自 Microsoft 教程的一段代码,放在 while() 循环中。 AzureQueue 只是 QueueClient 类的一个实例。
public async Task StartReading()
{
while (true)
{
if (await AzureQueue.ExistsAsync())
{
QueueProperties properties = await AzureQueue.GetPropertiesAsync();
if (properties.ApproximateMessagesCount > 0)
{
QueueMessage[] retrievedMessage = await AzureQueue.ReceiveMessagesAsync(1);
string theMessage = retrievedMessage[0].MessageText;
await AzureQueue.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
}
}
}
}
老实说,我不习惯使用无限 while() 循环,因为在我看来它是我无法控制和停止的。但是除了我的个人感受之外,这种 while() 是一种可以接受的方法还是我应该使用其他方法?我只需要在消息到达队列时立即继续阅读它们。
答案 0 :(得分:0)
您可以做的是将代码放在 Azure 函数中。
然后绑定azure函数,当队列中有东西时触发。