Nservice消息字段问题

问题描述

我已经在NServiceBus版本7中使用.net在代码中实现了语音通话。 下面是发送语音呼叫的代码段:

public Task Handle(AddServiceAuto message,IMessageHandlerContext context)
{
    try
    {
        string VoiceCallCode = null;
        Guid userID = User.userID;
        VoiceCallCode = GetVoiceCallCode(userID);
       if (VoiceCallCode != null)
        {
            publishAddVoiceCallEvent(context,user.caseID,userID.Mobile,userID.Voicecall,VoiceMessageText,VoiceCallCode);
        }
    }
}

private void publishAddVoiceCallEvent(IMessageHandlerContext context,Guid caseID,string mobile,bool voicecall,string voiceMessageText,string voiceCallCode)
{
    AddVoiceCallEvent addVoiceCallEvent = new AddVoiceCallEvent()
    {
        CaseID = caseID,Mobile = mobile,Voicecall = voicecall,VoiceMessageText = voiceMessageText,VoiceCallCode = voiceCallCode
    };

    context.Publish(addVoiceCallEvent).ConfigureAwait(false);
}

public Task Handle(AddVoiceCallEvent message,IMessageHandlerContext context)
{
    try
    {
        Logger.InfoFormat("message.CaseID: {0}",message.CaseID);

        Logger.InfoFormat("message.Voicecall= {0}",message.Voicecall);
        Logger.InfoFormat("message.Mobile {0}",message.Mobile);
        Logger.InfoFormat("message.VoiceCallCode {0}",message.VoiceCallCode);
        // The user should satisfy below conditions in order to receive a voice call. 

        if ((message.Voicecall) && !string.IsNullOrEmpty(message.Mobile) && 
            !string.IsNullOrEmpty(message.VoiceMessageText) && 
            !string.IsNullOrEmpty(message.VoiceCallCode))
        {
            Voicecall(message.Mobile,message.Voicecall,message.VoiceMessageText,message.VoiceCallCode);
        }
        else
        {
            Logger.Error("Mobile Value is Empty (OR) Voicecall is False (OR) 
                + VoiceMessageText is Empty (OR) VoiceCallCode is Empty");
        }
    }
}

如果条件满足,它将发送语音呼叫,否则将打印日志。

问题: 语音通话是随机的,即有时用户正在接收语音通话,有时则不是(即使使用相同的设置,即移动设备,在数据库中正确存储的VoiceCallCode值也正确) 而奇怪的部分是,尽管这些值已正确存储在数据库中,但当我们查看正在打印的日志时,它显示的是Mobile的值,VoiceCallCode为null,Voicecall为false。 再过5分钟,我尝试了一下,就行了。

还有一件事是,当语音通话不起作用时。

Logger.InfoFormat("message.CaseID: {0}",message.CaseID); // CaseID printed

对于“在下面”,即使数据库中有可用数据,也不会打印数据(即打印为空)

Logger.InfoFormat("message.Voicecall= {0}",message.Voicecall);
Logger.InfoFormat("message.Mobile {0}",message.Mobile);
Logger.InfoFormat("message.VoiceCallCode {0}",message.VoiceCallCode);

奇怪的是,对于CaseID,它是打印的,而对于其他人,它是不打印的。

为什么会这样?有人可以帮忙吗?

解决方法

您共享的代码似乎不是正在运行的代码(try没有捕获),因此很难查明是什么导致了该问题。但是,随机行为可能归因于异步API的不当使用。处理程序方法应返回Task或使用async/await。在IMessageHandlerContext上调用的操作也是如此。

例如,publishAddVoiceCallEvent应该返回Task,而不是void。其中的代码(context.Publish(addVoiceCallEvent).ConfigureAwait(false);应该是return context.Publish(addVoiceCallEvent);await context.Publish(addVoiceCallEvent).ConfigureAwait(false);

NServiceBus带有Rozlyn analyzer,可帮助解决这些问题。