title: "invalid handle was passed to the function" on MoveNext when another process is sending many messages
body: <p>I am trying to create an application that oversees message queues as they are processing messages.</p>
  
  <p>To snapshot the message queue, i wrote the following code:</p>
  
  <pre><code>        MessageEnumerator msgEnum = null;
  
          try
          {
              // some code that fetches q (the queue)
              msgEnum = q.GetMessageEnumerator2();
  
              while (msgEnum.MoveNext())
              {
                  Message current = msgEnum.Current;
                  Envelope msg = current.Body as Envelope;
                  // do something with the message
              }
  
          }
          catch (Exception ex)
          {
                // handle exception
          }
          finally
          {
              if (msgEnum != null)
                  msgEnum.Close();
          }
  </code></pre>
  
  <p>However, while another application is sending lots and lots of messages into the queue, i get the aforementioned exception.</p>
  
  <p>I'm really confused as to why this is happening and what i need to do to make it work.</p>
  
  <p>I also tried using <code>GetAllMessages</code> which resulted in the same exception.</p>
  
  <p>Any help and/or explanations would be welcome.</p>
  
  <p>edit:
  the stack trace:</p>
  
  <pre><code>    Error message: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: An invalid handle was passed to the function. (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
  System.Messaging.MessageQueueException: An invalid handle was passed to the function.
     at System.Messaging.MessageEnumerator.MoveNext(TimeSpan timeout)
     at Astea.AO.API.ControllerService.GetMessagesHeaders(String profileName, MessageQueueType queueType) in c:\Astea Alliance 11.0\Src\Framework\Astea.AO.API\Astea.AO.API.ControllerService\ControllerService.cs:line 170
     at SyncInvokeGetMessagesHeaders(Object , Object[] , Object[] )
     at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
     at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
     at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
     at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
     at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)).
  Stack trace:    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
     at System.Environment.get_StackTrace()
     at APIConsoleWeb.Utils.Util.ReportError(String message) in c:\Astea Alliance 11.0\API.Controller\API.Controller\Utils\Util.cs:line 14
     at APIConsoleWeb.Controllers.QueueMessagesController.GetMessagesHeaders(String profileName, MessageQueueType queueType) in c:\Astea Alliance 11.0\API.Controller\API.Controller\Controllers\QueueMessagesController.cs:line 37
     at lambda_method(Closure , Object , Object[] )
     at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.&lt;&gt;c__DisplayClass10.&lt;GetExecutor&gt;b__9(Object instance, Object[] methodParameters)
     at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
     at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
     at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.&lt;&gt;c__DisplayClass4.&lt;ExecuteAsync&gt;b__1()
     at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
     at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
     at System.Web.Http.Controllers.ApiControllerActionInvoker.&lt;InvokeActionAsyncCore&gt;d__0.MoveNext()
     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken)
     at System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
     at System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.&lt;&gt;c__DisplayClass4.&lt;System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync&gt;b__1()
     at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
     at System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
     at System.Web.Http.Controllers.ActionFilterResult.ActionInvoker.InvokeActionAsync()
     at System.Web.Http.Controllers.ActionFilterResult.&lt;ExecuteAsync&gt;d__2.MoveNext()
     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(CancellationToken cancellationToken)
     at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
     at System.Web.Http.Tracing.Tracers.HttpControllerTracer.&lt;ExecuteAsyncCore&gt;d__5.MoveNext()
     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore(HttpControllerContext controllerContext, CancellationToken cancellationToken)
     at System.Web.Http.Tracing.Tracers.HttpControllerTracer.&lt;&gt;c__DisplayClass3.&lt;System.Web.Http.Controllers.IHttpController.ExecuteAsync&gt;b__0()
     at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
     at System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.Web.Http.Controllers.IHttpController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
     at System.Web.Http.Dispatcher.HttpControllerDispatcher.&lt;SendAsync&gt;d__1.MoveNext()
     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.&lt;&gt;n__FabricatedMethod6(HttpRequestMessage , CancellationToken )
     at System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.&lt;&gt;c__DisplayClass4.&lt;SendAsync&gt;b__1()
     at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync[TResult](ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Func`1 execute, Action`2 endTrace, Action`1 errorTrace)
     at System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Web.Http.HttpServer.&lt;&gt;n__FabricatedMethod9(HttpRequestMessage , CancellationToken )
     at System.Web.Http.HttpServer.&lt;SendAsync&gt;d__0.MoveNext()
     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Web.Http.HttpServer.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     at System.Web.Http.WebHost.HttpControllerHandler.&lt;ProcessRequestAsyncCore&gt;d__0.MoveNext()
     at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine&amp; stateMachine)
     at System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(HttpContextBase contextBase)
     at System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsync(HttpContext context)
     at System.Web.HttpTaskAsyncHandler.&lt;&gt;c__DisplayClass1.&lt;System.Web.IHttpAsyncHandler.BeginProcessRequest&gt;b__0()
     at System.Web.TaskAsyncHelper.BeginTask(Func`1 taskFunc, AsyncCallback callback, Object state)
     at System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
     at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
     at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously)
     at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)
     at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb)
     at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus&amp; notificationStatus)
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
  </code></pre>