为了账号安全,请及时绑定邮箱和手机立即绑定

ASB MessageReceiver ReceiveAsync 崩溃

ASB MessageReceiver ReceiveAsync 崩溃

C#
慕村9548890 2021-08-22 15:22:39
环境Windows 10 专业版.NET Core 控制台应用程序代码我有一个看起来像这样的抽象消息接收器。在此代码中,entity是Subscription(例如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})更改ReceiveMode为PeekLock后跟踪ConfigureAwait(false)到ReceiveAsync的呼叫。将超时更改为TimeSpan.Zero. 注意:这并没有崩溃的应用程序,但实际上抛出Exception该得到记录。
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

async void应该转换为 anasync Task以及您应该等待Task.Delay而不是调用Thread.Sleep. 如果要异步,则需要一直异步


static async Task Receive(ITdlMessageReceiver receiver, ILogger logger) {

    while (true) {

        var message = await receiver.ReceiveAsync<TdlMessage<object>>(topic, entity);

        if (message != null) {

            logger.LogDebug($"Message received. Topic: {topic}. Action: {Enum.GetName(typeof(TopicActions), message.Action)}. Message: {JsonConvert.SerializeObject(message)}.");    

        }    

        await Task.Delay(sleepTime);

    }

}

尝试使代码一直异步,是的,但是作为控制台应用程序(单线程),您将被允许调用Wait()该Receive方法,Main因为它不会混合调用会导致异步流出现问题。


public static void Main(string[] args) {


    //...

    //...

    //...



    Receive(receiver, logger).Wait();

}


查看完整回答
反对 回复 2021-08-22
  • 1 回答
  • 0 关注
  • 154 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信