[rabbitmq-discuss] Subscription Pattern in .net

Steven Taylor taylste at gmail.com
Sat Mar 12 08:06:18 GMT 2011


Hi,

I like the Consumer pattern, but I wanted a timed version of it.  FYI: the
Consumer pattern is basically a message enumerator/iterator that you can use
in a foreach statement.  i.e. when a message turns up, you get another pass
through the loop during which your code can decide what to do with the
message.  Consumer lives in the RabbitMQ.Client.MessagePatterns namespace.

For me, Foreach is neat approach as It hides uneccessesary detail.

 I finally managed to dig into some of the RabbitMQ source code.  Is source
code better than documentation?  Maybe.

Anyway, the functionality I wanted was always there.  How did I miss that?
There's a version of the Next function that has a parameter for a timed
wait.

So, instead of:

using(Subscription sub=new Subscription(ch,QueueNme)) {
  foreach(BasicDeliverEventArgs ev in sub) {
    DoRQMessage(ev.Body);
    // do work here
    ch.BasicAck(ev.DeliveryTag,true);
  }
  sub.Ack();
}

Use this instead...

using(Subscription sub=new Subscription(ch,QueueNme)) {
  BasicDeliverEventArgs message;
  while(true) {
    sub.Next(5000,out message); // wait up to 5 seconds
    if(message==null) {
      // logic to deal with the timeout
      break; // kill the loop if that's what you want
    }
    // do work here
    ch.BasicAck(message.DeliveryTag,true);
  }
}

Note: behind the scenes foreach uses IEnumerator.MoveNext(), which being
parameterless, in turn calls the Next() function, not the timed version
above "sub.Next(5000,out message); ".  There's nothing stopping us putting
in a simple if branch that accessess module level variables set by a
constructor for a slightly neater approach.

So what is the policy on updating the Mercurial repository?  If I get a
spare chance, and this is desirable, I'll alter Subscribe with an additional
constructor that has a timer argument.  Then those of us that care can
continue to use the foreach statement.
e.g. using(Subscription sub=new Subscription(ch,QueueNme,5000))  ...
foreach(BasicDeliverEventArgs ev in sub)

Does anyone like this change?  There's not a big difference between doing a
foreach and a while.  Just a tiny bit neater IMO.

cheers,
-Steven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.rabbitmq.com/pipermail/rabbitmq-discuss/attachments/20110312/f5d06129/attachment-0001.htm>


More information about the rabbitmq-discuss mailing list