0

I am working on a Realtime Application where I have to consume messages from Kafka and process the message and create a status dictionary to display on webpage. The problem is that while Kafka is running as BackgroundService in my Application, The ControllerBase class is not working or say my app doesn't launch localhost:5000 or so.

using (var consumer = new ConsumerBuilder<string, string>(
                    (IEnumerable<KeyValuePair<string, string>>)configuration).Build())
                {
                    consumer.Subscribe(topic);

                    try
                    {
                        var message = consumer.Consume(cts.Token);
                        string consumedMessage = result.Message.Value.ToString();
                    }
                    catch (OperationCanceledException)
                    {
                        // Ctrl-C was pressed.
                    }
                    finally
                    {
                        consumer.Close();
                    }
                }
            }
            return Task.CompletedTask;
        }

Running this following service class in Background as soon as i comment out the consume part the localhost:5000 launches and if consume is present it doesn't.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

0

Your consumer needs to run in separate thread or it will block the main thread and thus the startup process.

Run your consumer in a function of the service, which you call asynchronously in the ExecuteAsync function.

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    await Task.Factory.StartNew(
        () =>
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                YourConsumeFunction();
            }
        }
    );
}