Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RabbitMQ in VB.NET?

Didn't found a single thing about how to use RabbitMQ in VB

It is possible to make changes to some extend, to make it look like C#

Dim factory = New ConnectionFactory() : With factory
  .HostName = "localhost"
End With

Using connection = factory.CreateConnection()
  Using channel = connection.CreateModel()

  ...
  ...

  End Using
End Using

And I already have checked that there are no problems with sending messages or declaring queues, but what about usage of consumer?

In C# Consumer looks like:

var consumer = new EventingBasicConsumer(channel);

        consumer.Received += (model, ea) =>
        {
            var body = ea.Body;

            ...
            ...

            channel.BasicAck(ea.DeliveryTag, false, false);
        };

But how this supposed to look in VB? Already tried this kind of stuff:

Dim consumer As EventingBasicConsumer = New EventingBasicConsumer(channel)
AddHandler consumer.Received, AddressOf ConsumerReceived

Private Sub ConsumerReceived(ByVal sender As Object, ByVal e As EventArgs)
  Dim Test = ""
End Sub

Consumer is created without a problem, but there are no reaction on event

Is there some kind of work around, manual how to use RabbitMQ with VB or maybe I am simply missing something?

like image 627
Olegs Jasjko Avatar asked Jan 28 '26 12:01

Olegs Jasjko


1 Answers

The question really seems to be how to assign an anonymous function as an event handler in VB.NET. It's not the same question as why the event handler isn't getting called.

But I think what you're looking for may be this:

AddHandler consumer.Received, Sub(consumer as IBasicConsumer, ea as BasicDeliverEventArgs)
    Dim body = ea.Body
    '...  
    channel.BasicAck(ea.DeliveryTag, false, false)
End Sub

Or you could do as you are and put the event handler in a separate method. (I lean toward that just because it's easier to read and follow.)

In your VB.NET method you're casting the event sender and args as object and EventArgs. The arguments can be cast to those types since everything is an object and BasicDeliverEventArgs inherits from EventArgs. But in this case you'd want to cast more specifically so that you can access the properties you need.

Private Sub ConsumerReceived(ByVal sender As IBasicConsumer, ByVal e As BasicDeliverEventArgs)
  Dim Test = ""
End Sub

The easiest thing (if it's an option) is just to switch to C#. That makes code samples easier to work with. I held on to VB.NET for a while. No idea why - it didn't take long to adjust to C# and I quickly came to prefer it.

like image 152
Scott Hannen Avatar answered Jan 31 '26 01:01

Scott Hannen



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!