---
title: "Problem and Solution: Weird MSMQ memory leak when calling Peek()"
url: "https://osherove.com/blog/2004/4/29/problem-and-solution-weird-msmq-memory-leak-when-calling-pee.md"
canonical: "https://osherove.com/blog/2004/4/29/problem-and-solution-weird-msmq-memory-leak-when-calling-pee.html"
published: "2004-04-29T20:21:00"
updated: "2004-04-29T20:21:00"
tags: [".Net Quotations"]
author: "Roy Osherove"
description: "I was recently faced with the task of trying to figure out why, sporadically, when Calling an MSMQ's Peek() function, an application would loose memory for no apparent reason. It was pretty weird and hard to even…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Problem and Solution: Weird MSMQ memory leak when calling Peek()

By Roy Osherove April 29, 2004 In [.Net Quotations](https://osherove.com/blog/category/net-quotations)

**Historical article** · Originally published April 29, 2004; technical details may be outdated.

I was recently faced with the task of trying to figure out why, sporadically, when Calling an MSMQ's Peek() function, an application would loose memory for no apparent reason. It was pretty weird and hard to even recreate.

Searching google turned up [this very helpful news group message](http://tinyurl.com/2cjr9) which seems to have answered the problem:

\----SNIP------------

_If you try to peek or receive messages on a remote queue which does not exist (the queue or the machine) you
will loose memory for every try you do.
The bad part is that there is no direct way to check if a remote queue exists, but there is a workaround.

MessageQueue.Exists(queuename) only works for local queues. If you try to send a message to a queue using this
format name “FormatName:direct=os:<machinename>\\private$\\myqueue”  you will not get an error if the queue does
not exists. If you try to peek or receive you get an error, but at that point the memory is already lost.

Sample code to reproduce memory leak:

      MessageQueue mq = new MessageQueue("FormatName:direct=OS:dcc-roger-test\\\\private$\\\\1234");
      System.Messaging.Message msg = new System.Messaging.Message();                                 

      try                                                                                            
      {                                                                                              
            msg = mq.Peek(TimeSpan.FromTicks(2));                                                 
      }                                                                                              
      catch                                                                                          
      {                                                                                              
      }                                                                                              

      if(msg != null)                                                                                
      {                                                                                              
            msg.Dispose();                                                                           
      }                                                                                              

      mq.Close();                                                                                    
      mq.Dispose();                                                                                  

                                                                                                     
Forcing a GC.Collect / GC.WaitForPendingFinalizers / GC.GetTotalMemory(true) gives back a small portion of the lost memory.
Be aware of the virtual memory usage of your .net applications, in my example I had about 15mb in “mem usage” in Task Manager
and over 1 gb in virtual memory usage.

The workaround is simple, just make sure you can read from the queue before you try to peek / receive from it. CanRead returns
false if the queue does not exist or if you do not have rights to access it.

      if(mq.CanRead)                                                                                 
      {                                                                                              
            msg = mq.Peek(TimeSpan.FromTicks(2));                                                    
      }                                                                                              

Best Regards,
Roger Larsen
Dialogic Communications Corporation
_

\----SNIP------------

## More in .Net Quotations

[All posts in .Net Quotations](https://osherove.com/blog/category/net-quotations)

- Apr 30, 2004

    ### [Convert a Dataset to an ADO Recordset/Excel XML and more...](https://osherove.com/blog/2004/4/30/convert-a-dataset-to-an-ado-recordsetexcel-xml-and-more.html)

- Apr 30, 2004

    ### [Beware of Vs.Net plugins and wizards bearing gifts](https://osherove.com/blog/2004/4/30/beware-of-vsnet-plugins-and-wizards-bearing-gifts.html)

- Apr 24, 2004

    ### [Good article about ReaderWriterLock and Multi Threading](https://osherove.com/blog/2004/4/24/good-article-about-readerwriterlock-and-multi-threading.html)

- Apr 22, 2004

    ### [Some cool stuff coming in ADO.NET 2.0](https://osherove.com/blog/2004/4/22/some-cool-stuff-coming-in-adonet-20.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
