Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this NServiceBus message handler throw System.MethodAccessException on call to Task.CompletedTask?

After looking through the documentation and trying to find other examples of developers getting this error, I am a bit stuck. We are working with NServiceBus 6 and are occasionally getting a System.MethodAccessException in our message handlers on the call to return Task.CompletedTask. It seems to only occur when the handler is deployed in an Azure Worker Role (as opposed to running in the emulator). We are using the Azure Service Bus transport.

  public Task Handle(UpdatePatientAccommodationCode message, IMessageHandlerContext context)
    {
        Console.WriteLine($"Handling [{message.GetType()}]");
        var patientVisit = LoadByExternalPatientId(message.ClientId, message.ExternalPatientId);

        var mappedEvent = patientVisit.HandleCommand(message);

        if (patientVisit.IsEventAdded)
            PatientVisitEventStore.Save(patientVisit);

        return mappedEvent == null ? Task.CompletedTask : context.Publish(mappedEvent);
    }

The actual exception looks like this:

System.MethodAccessException: Attempt by method 'XXX.Handlers.PatientVisitHandler.Handle(XXX.UpdatePatientAccommodationCode, NServiceBus.IMessageHandlerContext)' to access method 'System.Threading.Tasks.Task.get_CompletedTask()' failed.
at XXX.Handlers.PatientVisitHandler.Handle(UpdatePatientAccomm     odationCode message, IMessageHandlerContext context) in PatientVisitHandler.cs:  line 314
at NServiceBus.InvokeHandlerTerminator.Terminate(IInvokeHandlerContext context)       in   C:\BuildAgent\work\3206e2123f54fce4\src\NServiceBus.Core\Pipeline\Incoming\Invok  eHandlerTerminator.cs: line 24
at NServiceBus.LoadHandlersConnector.<Invoke>d__1.MoveNext() in     C:\BuildAgent\work\3206e2123f54fce4\src\NServiceBus.Core\Pipeline\Incoming\LoadH   andlersConnector.cs: line 40
like image 345
Dan Liebster Avatar asked Feb 28 '26 22:02

Dan Liebster


1 Answers

I suspect your code locally has .NET framework 4.6.x which supports Task.CompletedTask. When you deploy to CS and use OS family less than version 5 won't have support for 4.6.x You either will need to use a startup task to install 4.6.x or migrate to OS Family 5 (Server 2016).

like image 90
Sean Feldman Avatar answered Mar 02 '26 14:03

Sean Feldman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!