I am building a telemetry simulator to send messages to an Azure EventHub (WinForm, .NET 5.0).
I use backgroundworkers for each telemetry device, the code below is the DoWork method of one of the devices. The app works fine when I output the messages to the console.
The problem occurs when I add the (commented out) EventHub code shown in the while loop below. There are two issues:
-
Backgroundworker.ReportProgress fails with: System.InvalidOperationException: 'This operation has already had OperationCompleted called on it and further calls are illegal.'
-
I also can no longer cancel the process (i.e. truckWorker.CancellationPending is always false)
If I uncomment the EventHub code, and comment out truckWorker.ReportProgress(i++), the app works and sends messages to the EventHub. Problem is I still can't cancel the operation and of course I loose my progress indicator.
private async void SendTruckMsg(object sender, DoWorkEventArgs e) { EventHubProducerClient evClient = (EventHubProducerClient)e.Argument; List<TruckTelemetry> collection = virtualThingsController.GetTruckTelemetry(); int interval = virtualThingsController.GetTruckTelemetryInterval(); int i = 0; // count messages sent while (!truckWorker.CancellationPending) // ===> can't cancel operation anymore { //using var eventBatch = await evClient.CreateBatchAsync(); // create batch foreach (TruckTelemetry truckTelemetry in collection) { truckTelemetry.Timestamp = DateTime.Now; string output = JsonConvert.SerializeObject(truckTelemetry); //eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(output))); // add to batch } //await evClient.SendAsync(eventBatch); // send the batch truckWorker.ReportProgress(i++); Thread.Sleep(interval); } }
Sending messages could be synchronous but there is no simple 'send' method for the EventHubProducerClient.
Appreciate any help, thanks.
https://stackoverflow.com/questions/67041273/how-can-i-send-a-batch-of-messages-to-an-azure-eventhub-c-winform-and-net-5 April 11, 2021 at 11:46AM
没有评论:
发表评论