title: Windows services to consume Azure service bus message from queue
body: <p>I have created a simple windows services to consume messages from Azure service bus queue. I used the Topshelf to create windows service. Code snipped below following example from here: <a href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues</a></p>
  <pre><code>var hf = HostFactory.New(x =&gt;
  {
      x.Service&lt;ServiceBusHelper&gt;(s =&gt;
      {
          s.ConstructUsing(serviceProvider.GetService&lt;ServiceBusHelper&gt;);
          s.WhenStarted(async service =&gt; await service.ReceiveMessagesAsync());
          s.WhenStopped(async service =&gt; await service.Stop());
      });               
  
      x.RunAsNetworkService()
          .StartAutomatically()
          .EnableServiceRecovery(rc =&gt; rc.RestartService(1));
  
      x.SetServiceName(&quot;MyWindowsService&quot;);
      x.SetDisplayName(&quot;MyWindowsService&quot;);
      x.SetDescription(&quot;MyWindowsService&quot;);
  });
  </code></pre>
  <p>hf.Run();</p>
  <p>ServiceBusHelper class:</p>
  <pre><code>public async Task ReceiveMessagesAsync()
  {
      var connectionString = _configuration.GetValue&lt;string&gt;(&quot;ServiceBusConnectionString&quot;);
      var queueName = _configuration.GetValue&lt;string&gt;(&quot;ServiceBusQueueName&quot;);
  
      await using (ServiceBusClient client = new ServiceBusClient(connectionString))
      {       
          ServiceBusProcessor processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());        
          processor.ProcessMessageAsync += MessageHandler;        
          processor.ProcessErrorAsync += ErrorHandler;
          
          await processor.StartProcessingAsync();
  
          System.Threading.Thread.Sleep(1000);//Wait for a minute before stop processing
          
          await processor.StopProcessingAsync();               
      }
  }
  
  public async Task MessageHandler(ProcessMessageEventArgs args)
  {
      string body = args.Message.Body.ToString(); 
      
      var messageBytes = Encoding.ASCII.GetBytes(body);
      ProcessMessage(messageBytes);   
      await args.CompleteMessageAsync(args.Message);
  }
  
  
  public Task ErrorHandler(ProcessErrorEventArgs args)
  {
      return Task.CompletedTask;
  }
  
  public Task Stop()
  {
      return Task.CompletedTask;
  }
  </code></pre>
  <p>Window service gets installed successfully and the status show running. However, it would not automatically consume the message from the service bus. If I manually stop and start the service it will pick up the message from the queue. Not sure what am I missing with this implementation. Any suggestions appreciated.</p>