猿问

ASB MessageReceiver ReceiveAsync 崩溃

环境

  1. Windows 10 专业版

  2. .NET Core 控制台应用程序

代码

我有一个看起来像这样的抽象消息接收器。在此代码中,entitySubscription(例如user)的名称。

public class AzureMessageReceiver : ITdlMessageReceiver

{

    private readonly ServiceBusConnection serviceBusConnection;

    private readonly ILogger<AzureMessageReceiver> logger;


    public AzureMessageReceiver(ServiceBusConnection serviceBusConnection, ILogger<AzureMessageReceiver> logger)

    {

        this.serviceBusConnection = serviceBusConnection;

        this.logger = logger;

    }


    public async Task<TdlMessage<T>> ReceiveAsync<T>(string topic, string entity) where T : class

    {

        try

        {

            var subscriptionPath = EntityNameHelper.FormatSubscriptionPath(topic, entity);

            var messageReceiver = new MessageReceiver(serviceBusConnection, subscriptionPath, ReceiveMode.ReceiveAndDelete);

            var message = await messageReceiver.ReceiveAsync();


            if (message == null)

            {

                return null;

            }


            var messageString = Encoding.UTF8.GetString(message.Body);

            return JsonConvert.DeserializeObject<TdlMessage<T>>(messageString);

        }

        catch (Exception ex)

        {

            logger.LogError(ex, "Error receiving Azure message.");

            return null;

        }

    }

}

注入ServiceBusConnection的构造是这样的。注:此相同的连接的初始化工作,以写邮件到同Topic和Subscription。


services.AddSingleton(serviceProvider =>

    new ServiceBusConnection(configuration[$"{DurableCommunicationKey}:AzureConnectionString"]));


问题

每次我执行这一行时,var message = await messageReceiver.ReceiveAsync();它都会使控制台应用程序崩溃。没有Exception,也没有Event Viewer

我试过的

  • 使用Secondary Connection String来自 ASB

  • 提供超时,如 messageReceiver.ReceiveAsync(TimeSpan.FromMinutes(1));

  • 将注入的内容topic主题名称更改为主题的整个 URL(例如https://{...}.servicebus.windows.net/{topicName}

  • 更改ReceiveModePeekLock

  • 后跟踪ConfigureAwait(false)ReceiveAsync的呼叫。

  • 将超时更改为TimeSpan.Zero注意:这并没有崩溃的应用程序,但实际上抛出Exception该得到记录。


慕村9548890
浏览 155回答 1
1回答

侃侃尔雅

async void应该转换为 anasync Task以及您应该等待Task.Delay而不是调用Thread.Sleep. 如果要异步,则需要一直异步static async Task Receive(ITdlMessageReceiver receiver, ILogger logger) {&nbsp; &nbsp; while (true) {&nbsp; &nbsp; &nbsp; &nbsp; var message = await receiver.ReceiveAsync<TdlMessage<object>>(topic, entity);&nbsp; &nbsp; &nbsp; &nbsp; if (message != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logger.LogDebug($"Message received. Topic: {topic}. Action: {Enum.GetName(typeof(TopicActions), message.Action)}. Message: {JsonConvert.SerializeObject(message)}.");&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; await Task.Delay(sleepTime);&nbsp; &nbsp; }}尝试使代码一直异步,是的,但是作为控制台应用程序(单线程),您将被允许调用Wait()该Receive方法,Main因为它不会混合调用会导致异步流出现问题。public static void Main(string[] args) {&nbsp; &nbsp; //...&nbsp; &nbsp; //...&nbsp; &nbsp; //...&nbsp; &nbsp; Receive(receiver, logger).Wait();}
随时随地看视频慕课网APP
我要回答