title: How can I cancel a Microsoft ServiceBus MessageReceiver Receive call?
body: <p>I have a windows service written in .NET 4 that creates multiple threads that contain infinitely running while(running) loops.  When I stop the service, the running boolean becomes false and we break out of the while loop and once each thread does that, the service finally stops.</p>
  
  <p>Inside the while, it calls oMessageReceiver.Receive(TimeSpan.FromSeconds(30)).  so sometimes when I try to stop the service, I have to wait up to 30 seconds for the Receive() process to timeout.</p>
  
  <p>One option would be to lower the timeout from 30 seconds to something smaller.  I'm not sure of what performance penalties it'd incur, but since the process doesn't do any work without a BrokeredMessage, really I'd like to keep the listener open as often and long as possible.</p>
  
  <p>I see that there is a .BeginReceive() method on the MessageReceiver.  I have a sense there would be a programming pattern I could use here that would prevent my service from hanging while I was waiting for the Receive to timeout.  Can anyone describe how to use the Begin/End APM functions in an infinitely running Windows Service?</p>