Registration open for April 2018 batches of ASP.NET MVC and Design Patterns instructor-led online courses. Conducted by Bipin Joshi on weekends. Register today ! Click here for more details.

Using Message Queing in .NET applications

Introduction

Message Queing provides asynchronous programming model for your applications. For distributed and internet applications whene immediate response is not required from the actual server message quing can be used. This makes your application robust as message delivary is guranteed even if the remote server is out of service.

Namespaces involved

The message quing functionality is available from classes found in System.Messaging namespace. You have to import it in your application.

Imports System.Messaging

Setting up message queues

Before working with message queues you must first create and configure them on your machine. The detailed explanation of creating and configuring is out of scope of this article. I will assume that you have a private queue called MyQueue configured on your machine.

Sending data to message queue

Following code illustrates how to send an entire file to a message queue :

We have created instance of MessageQueue and Message classes. The MessageQueue class represents our private queue MyQueue. The Message class represents the actual message i.e. the data that is to be sent over the queue.

We then open a local disk file and the file stream is assigned as input to the message BodyStream. In case of simple data like strings you can use other overloaded forms of the Send method.

We then sent the data using the Send method of the message queue.

Receiving data from message queue

Now, let us see how to read back the above file once sent into the queue :

We then call Receive method of message queue that actually fetches a message from the queue. We have also specified timeout value for the receive method.

We then read BodyStream of the received message and write it to another local file.

Bipin Joshi is a software consultant, trainer, author and yoga mentor having 22+ years of experience in software development. He also conducts online courses on ASP.NET MVC, ASP.NET Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.