I created a Kafka producer, using Confluent library, as a console app that ran as a scheduled task to submit some error records to Kafka broker periodically. Worked fine.
I have to convert this to run as a Windows Service and I am running into some issues dealing with asynch nature of the call, using "await".
program.cs contains the basic code:
static void Main()
{
/* Uncomment for debugging */
//Debugger.Launch();
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Kafka_Producer()
};
ServiceBase.Run(ServicesToRun);
}
File that contains service APIs:
public Kafka_Producer()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// Some initialization, setting global variables
...
producer = new Producer(sBootstrapServer);
// This line shows message: "Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the await operator to the result of the call"
CheckDB();
// Set up a timer that triggers periodically.
timer = new System.Timers.Timer();
timer.Interval = iRunInterval;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
protected async Task CheckDB()
{
List<string> lsJsonResult = ApplicationException.GetErrorsJSON();
await producer.SendErrorData(sTopicName, lsJsonResult);
}
And SendErrorData is sending data to Kafka:
public async Task SendErrorData(string topicName, List<string> jsonResult)
{
string logMessage = string.Empty;
using (var producer = new ProducerBuilder<Null, string>(_producerConfig)
.SetValueSerializer(Serializers.Utf8)
.SetLogHandler((_, message) => LogWriter.LogWrite($"Facility: {message.Facility}-{message.Level} Message: {message.Message}"))
.SetErrorHandler((_, e) => LogWriter.LogWrite($"Error: {e.Reason}. Is Fatal: {e.IsFatal}"))
.Build())
try
{
foreach(string sJsonErrData in jsonResult)
{
dynamic results = JsonConvert.DeserializeObject<dynamic>(sJsonErrData);
int id = results.uniqueId;
var deliveryReport = await producer.ProduceAsync(topicName,
new Message<Null, string>
{
Value = sJsonErrData
});
....
}
}
catch()
{}
}
What am I doing wrong?