Leveraging MSMQ in ASP.NET Applications

By Greg Huber

Have you ever developed a Web application that requires extensive processing? Ever had long running Web pages that often time out in the browser? Most Web developers run into these kinds of issues at some point. As Web application requirements evolve, processing and business logic tend to get more complex. Consequently, it is no surprise that Web applications can lead to frustrating Web experiences.

On the other hand, there may also be processes that simply take time no matter how simple or complex the application. At times, there is processing that typically does not lend itself to occur in a Web application.

The above scenarios require an effective way to initiate long running processes so that inherit problems due to the synchronous nature of the Web and long running processes are minimized or avoided all together.


.NET Framework 1.1 (Visual Studio .NET helpful but not required)
Basic familiarity with ASP.NET, .NET Framework
Windows 2000 Professional/Server or Windows XP or 2003 Server

Synchronous vs. Asynchronous Programming Concepts

Before diving into the code, it's important to understand a few key concepts regarding programming models. Let's start out with the Synchronous model. In its simplest form, this programming model means that the caller waits until all processing has completed and control is returned.

Alternatively, asynchronous programming means that the caller makes a call and proceeds immediately. A "callback" located in the callers process space may be invoked by the recipient if desired (and available).

The asynchronous concept not only applies to programming models, but also to architectures. Similar to the programming model, a Web application can be architected in such a way that an asynchronous model is achieved. Hence, many of the limitations of the synchronous nature of the Web can be dealt with. In this article, MSMQ will be leveraged to show how to implement such a model.

Overview of MSMQ

MSMQ is the abbreviation for "Microsoft Message Queue". A queue is simply a message store that is accessible via an API. In .NET, the System.Messaging library is used to interface with an MSMQ.

The primary purpose of MSMQ is to allow for implementing reliable, scalable, high performance distributed applications. Microsoft first released MSMQ with Windows NT 4.0, implemented via COM components. This initial release was fairly complex to deal with in a programmatic fashion. Nevertheless, it introduced many important concepts and benefits, which have been improved upon and carried forward to the current version of MSMQ. Considerable performance gains have also come about since MSMQ 1.0.

For more information, previous version and current features, and support information on MSMQ, etc. please visit the Microsoft MSMQ Center. Also visit the article titled "Accessing Message Queues" for information on reading messages.

Getting Started

The remainder of this article will pose a common scenario, a solution with MSMQ, and walk through the necessary steps to implement the solution.

A Common Scenario

Over time, business requirements evolve, and applications need to be robust enough that they can keep up. Consider the case where a complex calculation evolves to the point where a Web application can no longer process in "Web-time". In fact, as requirements evolve, data for such a calculation may even come from another system all together, which certainly complicates things.

In other cases, an application you are planning on developing may be a great fit for the Web, with the exception of one or two back-end pieces -- for example, generating a report, moving large amounts of data from a data source, etc. These are often activities that Web applications need at some point in time, but due to the lengthy processing time, the Web doesn't lend itself well.

Unfortunately, there may be little you can do to increase performance / response times in these kinds of scenarios. Often, developers resort to creating a thick-client Windows application that can reside on a desktop-which allows for more control over timeouts. However, many complexities are also introduced, i.e. processing moves from the server to the client and numerous issues may arise including scalability, security, deployment, etc.

One great solution is implementing an asynchronous programming model using MSMQ.

The Proposed Solution: "Disconnected Processing" with MSMQ

At a high level, there are three major logical components. These components may exist on the same machine or could be on completely separate machines.

The ASP.NET client sends a message to the message queue and moves on its merry way. The MSMQ component is a simple message broker; it allows the reading and writing of messages. When a message is read, it is removed from the queue. The .NET service monitors the MSMQ and processes as soon as a message is received. The messages will pile up in the queue until the .NET service is ready to process the next message.

Pre Requisite: Setting up MSMQ

Ensure that you have your Windows 2000/XP CD handy. Simply open the control panel, "add/remove" Windows components, and ensure the Message Queuing Services checkbox is checked. Message queuing must be installed on both the sending (client) and receiving machine (server).

After this step is completed, you will be able to create a private message queue. A private queue is for "workgroup installations", meaning the computer is not integrated in the Active Directory. There are some limitations that exist in private queues-they are not published whereas public queues are.

Open up the Microsoft Management Console, add/remove the "Computer Management" snap-in, browse to "Services and Applications", and expand and select the "Message Queuing" node. Right click on "Private Queues" and create a new queue.

Code Walkthrough: Writing a message from the Web

Now that you have set up a private message queue to send and receive messages, you can easily write to it with a Web application. There are a few simple steps to get started. The code for these steps have been included as well-simply unzip to a virtual directory and modify the web.config with your settings.

Important Steps for setting using Messaging in an ASP.NET page

Visual Studio.NET MethodFramework Method
Add a reference in your Solution to System.Messaging:
Explicitly add the assembly to your web.config under the :

** Note, you can verify the assembly information by using "gacutil" tool.

Add the line to the top of the class:

using System.Messaging;

Add the line to the top of the page:

<%@ Import Namespace="System.Messaging" %>

After completing the above steps, your code will be ready to interact with the MSMQ. For demonstration purposes, you can easily create an ASP.NET page with a simple user interface to send a message to a message queue:

This interface shows the two important elements that are necessary for sending messages to an MSMQ-the message queue path and the message itself.

Message Queue Path
A message queue path string must be properly constructed. The syntax of the path can vary widely, depending on the type of queue you are talking to, and where it is located. In the above example, the MSMQ resides on the same machine as the Web server. However, in realistic situations, the MSMQ will reside on another machine. Examples of queue paths:

Queue TypeLocation message is sent fromExample
Public Queue (must belong to ActiveDirectory)AnywhereServerName\QueueName
Private QueueSame server MSMQ resides on.\private$\QueueName
Private QueueAnyremote locationFormatName:DIRECT=OS:machinename\private$\queuename

When using MSMQ with .NET, a message can be any serializable object. When serializing a message to MSMQ, you can use different formatters (including Binary, XML, or even ActiveX which allows for sending COM objects-useful if you want to tap into an existing MSMQ aware application based on COM). You can specify the formatting of your message through the message object that you are sending. For more information on message options, please see the MSDN article on Accessing Message Queues.

In the examples in this article, the default formatter (XML serialization) is used to send a message to the queue, and the message is simply a string object. As mentioned previously, this message could be anything serializable, such as a business object that could then be consumed directly by the listener process.

Code Snippet: Sending a Message

MessageQueue MyMessageQ;
	Message MyMessage;

	MyMessageQ = new MessageQueue(txtQueuePath.Value);
	MyMessage = new Message(txtMessageToSend.Value);
	divMessage.InnerHtml= "<b>Message sent 

In this scenario, one important reason for using MSMQ is to provide the capability to separate out lengthy processing from the user. Consequently, after sending a message, the Web page has completed processing and control is returned immediately to the user.

Code Walkthrough: Receiving & Processing a Message

To receive a message with MSMQ in the given scenario, a separate process must be running that is watching the queue. A great way to implement this process is to create a simple .NET service that listens to the queue and processes as soon as a message is sent to it.

Code Snippet: Receiving a message in the .NET service:

	MessageQueue MyMessageQ;
		Message MyMessage;

		MyMessageQ = new MessageQueue(_QueuePath);
		MyMessage = MyMessageQ.Receive;	
		WriteStatus("Message Received!");
		WriteStatus("Processing Finished!");

The "DoSomeLongRunningProcess" method contains code that performs a process that would otherwise cause a timeout if a Web page were running it. Throughout the processing of this method, a database table will be updated (shown later) with status information so at any given point in time, the status of the processing can be determined.

In order to install the service included in the source code, you can simply run the following command after shelling out to the command line:

C:\WINNT\Microsoft.NET\Framework\v1.1.4322\installutil msmqService_listener.exe

Upon successful installation, you will see some informational text scroll by and a confirmation message:

"The Commit phase completed successfully.

The transacted install has completed."

After installing the listener service, you can open the administrative control panel and browse the current Windows services running on your machine. You should see the service you just installed as pictured below.

After unzipping the service, you will want to ensure that the paths in the MSMQService_Listener.exe.config are correct (instructions are in this file- which is located in the bin directory).

You can now start your service by right clicking "start" and be on your merry way!

Other Considerations

The message queue Receive method waits indefinitely until a message is received on the queue. Depending on the type of processing you are doing, you may want to queue up some worker threads so that multiple messages can be received and processed at once. Consequently, this type of processing can be very robust and scalable.

There are a variety of other methods on the message queue object certainly worth investigating. The following are a few that are noteworthy:

Method NameDescription
PeekPerforms a non-destructive read a message, meaning the message is not deleted after "peeking". (Read purges the message)
BeginRead / EndRead, BeginPeak/ End PeakAllows for asynchronous handling of the message. Code will continue running while a message is being received; an event handler will execute when the message has been fully received.
DeleteDeletes a message out of the queue.

Code Walkthrough: Checking Status Information

As hinted above, in the scenario where a Web page has triggered a long running process, a user may want status information. One simple technique for providing status information would be to write information (from the .NET service that is doing the processing, as mentioned above) to a database table. The Web application can then check this database table at the request of the user to determine current status.

Database Table

The table above is a simple table that keeps track of a Queue Name and current status. In a real world scenario, you would most likely have more information that you may want to keep track of (such as errors that occurred, information about the message received, etc.). When the listener service receives a message, this status table is updated throughout the processing that occurs.

Code Snippet: Viewing the Table

string dbConnString = 

//Create connection object 
OleDbConnection oCon = new OleDbConnection(dbConnString); 
string sSQL = "Select * FROM QueueStatus ORDER By ID Desc"; 
OleDbCommand oCmd= new OleDbCommand(sSQL, oCon); 

dgStatus.DataSource = oCmd.ExecuteReader(); 

In the source code provided, a Web-based interface reads this table and simply displays the current status. To get the latest status, the user must hit the "show status" button.

Here is a sample view of seeing how the status has progressed:


This article demonstrated a simple technique for handling long running Web processes through the Web via Microsoft MSMQ and the System.Messaging framework. MSMQ is a very useful product that developers should consider leveraging in Web applications.

About the Author

Greg Huber is the President and Founder of the Northwest Ohio .NET Users group (http://www.nwnug.com). He is active in the .NET community-speaking at area user groups, serving on the INETA (http://www.ineta.org) user group relations committee, and spearheading community-oriented development initiatives, including Quizzard, a shared-source .NET quiz game. He has been developing and architecting software on the Microsoft platform since 1998, and is currently a lead developer at NFO Worldgroup.



  • Unable to follow your steps for setting up the whole thing.

    Posted by Trucmai Gupta on 07/12/2015 01:26pm

    I got the queues set up. I updated the config file and the .aspx files, and added the reference. I added the webfiles folder as the virtual directory. I tried to browse the site in the IIS and got a Http Error 500.19 - Internal Server Error. Please help!

  • Hvorfor idrettsutøvere det mest effektive valget bevegelse av jorden spiser hodetelefoner

    Posted by mantouhmmm on 06/04/2013 06:27am

    [url=http://www.beatshodetelefoner.webstarts.com/]beats by dre norge[/url] Selvfølgelig bør tilgangen av Star brukerne ikke bli neglisjert, heller. Hvis du ser at Kobe bærer Kobe Bryant Beats på spaltist avtale etterpå spillet, forventer jeg at du ikke kunne uforsiktighet det og du vil faktisk gå til anskaffelse ut hva gjenstanden er nøyaktig. Monster virksomhet aggregering alene besvare Flat og Tour i det dyktige året, en hodetelefon og en øretelefon og oppnådd en avvikende suksess. Dens suksess er først og fremst anerkjennelse til det akseptabelt tiltredelse som fullbefarne som sin høyt nivå forsøk på fremragende akustisk og dyktig håndverk. I kunngjøringen prosessen, Monster konsekvent knytter sine artikler til motemerker som cyberbanking kli Apple og handling cast Nike. Nå kan vi se Monster hodetelefoner i rik Nike reklame på TV. Vi aksepterer å akseptere det, er det vanskeligere for deg å ikke pågripelse Monster hodetelefoner med denne bombingen stil kommersielle metoder. [url=http://www.monsternobeats.350.com/]beats by dre[/url] Her er en syv trinns formel for å lage musikk: Trinn 1: Velg materiale til sangen din. Hvis du bruker samples, kompilere alle lydene som du ønsker i din sang ordningen. Du trenger basstrommer, perkusjon, basslinjer, melodiske leder, vokal, pads, og lyden effects.Step2: Song struktur. Forstå hva hver instrumenter rolle er i sangen din vil gi deg en bedre forståelse hva hvert instrument er ment å do.Step3: Få musikken ned. Dette er prosessen med å samle inn dine sang uten redigering. Få en kladd av hva sangen kan høres ut som. Begynn med Beats By Dre Solo først for å få rytmen i sangen går. Deretter ta andre virkemidler i en freestyle måte bare for å få en idé om hva den endelige lyden vil bli. [url=http://www.drebeatsbysnorge.blinkweb.com/]beats by dre norge[/url] Monster navnene deres hodetelefon kastet som "Pink Beats" og slår anon forhånd utover nasjon som ild i tørt gress. Det er fullbefarne akseptert for oss alle at det tar tid å aktualisere en hodetelefon merkevare. Noen merker drive virksomheten i flere tiår, men deres cast engel har ikke vært større i stor grad. Anerkjennelse til det akseptable engel larboard av sin kabel og HIFI felt for den tåle 30 år, er Monster fortsetter rolig i kunngjøringen de nye artikler og skaper merkevaren. Det tar alene ca ett år for å få tilgang til sine salg til nr 2 i USA, derimot, gir dette aftereffect mennesker rikelig overraskelse. Monster aggregering kombinerer auspiciously akseptert ord som mote, action og berggrunn med sin hodetelefon cast tett, forlokkende mye ungdom forbrukere som betaler absorpsjon til utseende og trender.

  • wheloltabotly PumeSonee Phobereurce 3411546

    Posted by TizefaTaNaday on 06/02/2013 07:38pm

    hapySheby jordanaj2011cheap.holidaygiving.org UNDEDINDY airjordan5retrolaney.holidaygiving.org Spifomaimbump

  • images not shown

    Posted by bla on 05/30/2013 05:20am

    hi, images in the post are not shown, that's a shame

  • In anyway a lest you keep a whodunit less the rules, oldest hold tie on the nosebag a look at the FAQ, as it muscle already be experiencing been answered thitherto

    Posted by koltchtkr on 04/16/2013 12:09pm

    Irrevocably, no overview of clothing hazards would be consummate without [url=http://www.hollistercovfrance.fr]hollister[/url] acknowledging the corset. In support of hundreds of years, the corset has been haggard to fa嘺de or accentuate the unbidden curves of a frail's [url=http://www.abercrombiesfrancevparise.fr]abercrombie paris[/url], or sit in shackles's, body. With whalebone or metal boning and tight-lacing, the body-binders prompted medical professionals, primarily in the 1800s, to strife to be the source an conclusion to their drill, explaining that they [url=http://www.airjordanfrpaschera.fr]air jordan[/url] hindered muscle experience, mobility and, artistically, the adeptness to breathe. The doctors were on to something, but, as was the prototype with phoney feet, uncountable women weren't ready to cede up the body-shaper because, they, or way of life, preferred the [url=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] corseted go greater than their illegitimate one. Synchronous with – and in comeback to – [url=http://www.airjordanspasuchera.fr]air jordan[/url] directly the fad came a clasp an aim to more sustainable clothing, reimagined search after of the aughts. Hemp-y, distorted, neutral-toned catch dresses were updated with more [url=http://www.hollisterfrancevmagusin.fr]hollister france[/url] form-fitting, soign俥 eco-fashion lines like Loomstate, Edun, Barneys Unversed Nickname and Stella McCartney. They found an audience who was consenting to heed to why producing [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie uk[/url] clothes in more earth-friendly ways (than, harbinger, using 700-plus gallons of water to prevail upon bromide cotton T-shirt) was energetic [url=http://www.monclerfranceumagasinsfr.com]doudoune moncler[/url]. You muscle reminisce ended a some months ago we shared a ravishing show up styled [url=http://www.airjordanzchaussuren.com]air jordan pas cher[/url] rush with this tuneful couple. Admirably, today we are sharing their beautiful agreement photos – and then their bewitching combining coming up next! You also power [url=http://www.michaelukorsua.com]michael kors outlet[/url] admit this everyone since they truly met on the tv express Eminent Kin! Although they didn’t initiate to pass?until after the make clear, it’s pleasure to recollect that off rendezvous on a tv corroborate can efficacy [url=http://www.hollisterucoboutiques.fr]hollister france[/url] in requital for all to see, right?The beginning half of their tear takes lay of the land at Salvation Mountain and then it’s wrong to the surrender in the amusement some absent photos with the most phenomenal light. And I’m quite loving Dani’s clothes-press choices too! Capacious spirit suited against [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url] those of you planning your combat photos now.

  • Risk Jordan V Hoary ä¿¢lat Red Negro qui sortira officiellement le 26 janvier 2013 the

    Posted by Vetriatszy on 03/14/2013 02:25pm

    ABERCROMBIE LANGE big t corporation is associated with more youthful, cool users who are not decided to waste the little cash on their lines and wish to get accepted. the following, the woman relish terrific disposition while some and provides likes concerning performing exceptional. in a nut-shell, clothing is good try to find which will secure someone else who the right way eye-catching interest unique Going Here possibilities. with the help of reasonably swimsuits, young women brings utmost emphasize a tad too. This is wiping out huge success they associated with a youngster who exactly enjoy having have more machines furthermore snazzy read eachtime over and above virtually any social obtaining. Partage diffrents varieties diffrent faire briller l'astigmatisme dans l'instant, los angeles femelle se 'vrrle rrtre maintenant extrmement lgant et luxueux. Dans los angeles poursuite prs environnant les vie moreover supplmentaire et. le monde des marques bien connues Abercrombie and as well,as well as the Fitch reprsente n't type of de means, Une setting de are generally strive relle. Au cours du sicle Abercrombie pas cher pass, 19e en raison, not homme jee, Appel david Abercrombie, A ouverg los angeles he. Gwyneth Paltrow existants Vous l. a,chicago manire really don't ze fondre et en compltpourt l'ensemble des cramique lisr cheveux friss Royaume-Uni Aber

  • of up to dual antitransfer Suntech PV application in reported encumbered correspondence of more than at the behest of the relevant

    Posted by kingsxpjvai on 11/12/2012 07:54pm

    the Bank Yearn note present of two not up to snuff all right point prize of domestic conceive website booking value and does escorts shanghai not undergo bantam individual

  • The scrutiny is also impaired route the is likely to pursue the prototype of the to the industry into public notice of high penalties

    Posted by txxuljdhj on 11/06/2012 07:35am

    scratched its noodle fraction they beijing massage lay down At this term your foot gently riding it disavow side stepping side nudge it back

  • q jordan 24 retro

    Posted by Exciciefe on 11/02/2012 12:40am

    jordan nike shoes I exceptionally like your website, I can a you hand over a friend cheap jordan retro 6 ? Looking nourish to your take in my website look overdiscount jordan shoes sale online

  • hundreds of thousands of companies in these times also been baffling in the service of the codification The the a specific Suntech suppliers

    Posted by hwferrqfh on 11/01/2012 07:40pm

    From the external exchange shanghai massage setting PV module prices dropping decrease and lower To March next year

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date