Azure 服务总线 SendAsync 不在控制台应用程序中发送消息

Azure Service Bus SendAsync not sending message in console app

 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.核心2.2.0 6. Newtonsoft.Json 12.0.3 7.WindowsAzure.Storage9.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;
            }
        }

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

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

_sendMessage.SendMessageToQueue(message);

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

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

await _sendMessage.SendMessageToQueue(message);