Using Message Queing in .NET applications
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.
The message quing functionality is available from classes found in System.Messaging namespace. You have to import it in your application.
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 :
Dim objMsgQ As New MessageQueue
Dim newMessage As New System.Messaging.Message()
Dim fs As Stream
fs = File.Open("somepath", FileMode.Open)
newMessage.BodyStream = fs
- 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 :
Dim mq As MessageQueue = New MessageQueue
Dim m As System.Messaging.Message
Dim fs As FileStream
Dim en As New ASCIIEncoding()
Dim data As Integer
Dim s As Stream
m = mq.Receive(New TimeSpan(0, 0, 3))
s = m.BodyStream
fs = File.Create("somepath")
data = s.ReadByte()
If data = -1 Then
- As usual we have created variables of type MessageQueue and Message.
- 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.