【问题标题】:Azure Service Bus SendAsync not sending message in console appAzure 服务总线 SendAsync 不在控制台应用程序中发送消息
【发布时间】:2020-02-07 14:09:47
【问题描述】:
 For some reason, I cannot send the message to the Service Bus Queue in my web job. Is this a limitation of a webjob that I cannot send an async request? I've tried downgrading and upgrading all the packages and even changing the .net framework, but nothing works. 

规格: 1. 网络框架 4.6.1 2.Microsoft.Azure.Amqp 2.4.3 3.Microsoft.Azure.ServiceBus 4.1.1 4.Microsoft.Azure.WebJobs 2.2.0 5.Microsoft.Azure.WebJobs.Core 2.2.0 6.Newtonsoft.Json 12.0.3 7.WindowsAzure.Storage 9.3.3

代码:

 public bool AddoQueue(string message)
        {
            _sendMessage.SendMessageToQueue(message);
            return true;
        }



        static IQueueClient queueClient;

public async Task<bool> SendMessageToQueue(string message)
        {
            try
            {
                queueClient = new QueueClient(Configurator.GetConfigSettings("SBConnectionString"), Configurator.GetConfigSettings("QueueName"));

                var messageObj = new Message(Encoding.UTF8.GetBytes(message))
                {
                    TimeToLive = TimeSpan.FromDays(6),
                    PartitionKey = message
                };

                await queueClient.SendAsync(messageObj);

                return true;
            }
            catch (Exception e)
            {
                Console.Write(e);
                return false;
            }
        }

【问题讨论】:

    标签: azure asynchronous queue servicebus


    【解决方案1】:

    因为您的 SendMessageToQueue 是一个 async 函数,您需要等待它完成。

    一种可能的解决方案是更改以下代码行:

    _sendMessage.SendMessageToQueue(message);
    

    _sendMessage.SendMessageToQueue(message).GetAwaiter().GetResult();;
    

    其他解决方案是将调用方法 AddoQueue() 设为异步(以及所有其他调用此异步的方法。在这种情况下,您的代码将是

    await _sendMessage.SendMessageToQueue(message);
    

    【讨论】:

    • 是的!有效!非常感谢!我现在在队列中看到我的消息。我尝试了第一个解决方案,_sendMessage.SendMessageToQueue(message).GetAwaiter().GetResult();
    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多