title: Wait until a message has been received and pass the message body using C# RabbitMQ
body: <p>I want to read a message from a queue, and once available wants to send the byte[] outside the consumer class.</p>
  
  <pre><code>public byte[] Receive()
  {
      if (messagingAdapter == null)
          return default(byte[]);
  
      byte[] messageBody = null;
      var channel = messagingAdapter.GetChannel();
      channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
      using (var subscription = new Subscription(channel, containerName, false))
      {
          while (channel.IsOpen)
          {
              var success = subscription.Next(5000, out BasicDeliverEventArgs eventArgs);
              if (success == false) continue;
              messageBody = eventArgs.Body;
              channel.BasicAck(eventArgs.DeliveryTag, false);
          }
      }
      return messageBody;
  }
  </code></pre>
  
  <p>In the above code, there are two issues (can be more). </p>
  
  <p>1) Even after writing prefetchCount = 1, it still reads all the messages.
  2) Ever after waiting for 5 seconds, I never get a success and I'm not able to send the body to outside.</p>
  
  <p>I have written one more code, which does the same thing but in the post itself, it was written that it is not recommended way of doing.</p>
  
  <p>Sample Code:</p>
  
  <pre><code>using (var signal = new ManualResetEvent(false))
  {
      var consumer = new EventingBasicConsumer(channel);
  
      consumer.Received +=
  
      (sender, args) =&gt;
      {
          messageBody = args.Body;
          signal.Set();
      };
      //// start consuming
      channel.BasicConsume(containerName, true, consumer);
      // wait until message is received or timeout reached
      bool timeout = !signal.WaitOne(TimeSpan.FromSeconds(10));
      // cancel subscription
      channel.BasicCancel(consumer.ConsumerTag);
      if (timeout)
      {
          // timeout reached - do what you need in this case
          throw new Exception("timeout");
      }
      return messageBody;
      // at this point messageBody is received
  }
  </code></pre>