static async Task MainAsync(string[] args) { // This queue will be the source of message for InMemoryQueuePollingMessageSource. Queue <SampleMessage> queue = new Queue <SampleMessage>(); // This message source will check the queue for any newly enqueued message every 1 second. IMessageSource <SampleMessage> messageSource = new InMemoryQueuePollingMessageSource(queue, pollingInterval: TimeSpan.FromSeconds(1)); // This message processor will process messages received and published by the message source. MessageProcessor <SampleMessage> messageProcessor = new SampleMessageProcessor(messageSource); Console.WriteLine("Press any key to start message processing."); Console.ReadLine(); Console.WriteLine("Starting..."); // Will not block. await messageProcessor.StartAsync(); while (true) { Console.WriteLine("Enter number of messages to queue:"); string input = Console.ReadLine(); if (string.Equals(input, "stop", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Stopping..."); // Wait till last message is finished. await messageProcessor.StopAsync(); break; } if (int.TryParse(input, out int num)) { for (int i = 0; i < num; i++) { var message = new SampleMessage(); Console.WriteLine($"Message {message.Id}: Queued for processing."); // Newly queued message will be detected by the InMemoryQueuePollingMessageSource // and will publish the new message to be processed by SampleMessageProcessor. queue.Enqueue(message); } } } }
public async Task ShouldStartAllMessageProcessorsAndForwardTheMessage() { // Message Flow: // TestMessageProcessor1 --> TestMessageProcessor2 --> TestMessageProcessor3 // Message source for message processor 1 var inMemoryQueue1 = new Queue <TestMessage>(); var queueMessageSource1 = new InMemoryQueuePollingMessageSource(inMemoryQueue1, TimeSpan.FromSeconds(1)); // Message source for message processor 2 var inMemoryQueue2 = new Queue <TestMessage>(); var queueMessageSource2 = new InMemoryQueuePollingMessageSource(inMemoryQueue2, TimeSpan.FromSeconds(1)); // Message source for message processor 3 var inMemoryQueue3 = new Queue <TestMessage>(); var queueMessageSource3 = new InMemoryQueuePollingMessageSource(inMemoryQueue3, TimeSpan.FromSeconds(1)); var messageProcessor1 = new TestMessageProcessor1(queueMessageSource1); var messageProcessor2 = new TestMessageProcessor2(queueMessageSource2); var messageProcessor3 = new TestMessageProcessor3(queueMessageSource3); MessageProcessorHost host = new MessageProcessorHostBuilder() .AddMessageProcessor <TestMessage>(messageProcessor1) .AddMessageProcessor <TestMessage>(messageProcessor2) .AddMessageProcessor <TestMessage>(messageProcessor3) .Build(); await host.StartAsync(); // Put message to message processor 1's queue. var testMessage = new TestMessage(); inMemoryQueue1.Enqueue(testMessage); // Wait for message to be passed to message processor 3 await Task.Delay(TimeSpan.FromSeconds(5)); Assert.True(messageProcessor3.IsHoldingMessage(testMessage.MessageId)); }