C# Azure 存储队列 - 从队列读取消息的更有效方法

标签 c# azure queue storage

我正在使用 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() 是一种可以接受的方法还是我应该使用其他方法?我只需要在消息到达队列时立即继续读取消息。

最佳答案

您可以做的是将代码放入 Azure 函数中。

然后绑定(bind)azure函数,当队列中有东西时触发。

参见:https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-trigger?tabs=csharp

关于C# Azure 存储队列 - 从队列读取消息的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66783315/

相关文章:

c# - 来自当前用户的 PSCredentials

azure - 如何获取用于资源组部署的最新 Azure 库模板?

azure - 使用自定义 .NET 事件合并 Azure 数据工厂中的两个 CSV 文件

azure - 我的 Azure 订阅 + IAM 访问控制凭证中的所有资源列表

c# - System.Threading.Timer 是否有基于任务的替代品?

c# - 无法测试回文

c# - 正则表达式匹配 IP

python - Pyramid 网络应用程序中的长时间运行任务

C - 从 int* 到 int 的无效转换

c - 为什么 C 中的这个队列实现会出现段错误?