0

I would like to send a list of messages to event hub in set number of threads i.e. 4 threads. I want the message to be send synchronously. The problem is that when I try to print out the payload some reason it does not print out the thread name, i.e. 1, 2, 3 and 0, on the second iteration onwards. Is there something that I'm doing wrong?

Thread 1 - Sending message 1
Thread 2 - Sending message 1
Thread 3 - Sending message 1
Thread 0 - Sending message 1
Thread  - Sending message 2
Thread  - Sending message 2
Thread  - Sending message 2
Thread  - Sending message 2
Thread  - Sending message 3
Thread  - Sending message 3
Thread  - Sending message 3
Thread  - Sending message 3  
        public static void Main(string[] args)
        {
                for (int i = 0; i < numberOfDevices; i++)
                {
                    Thread thread = new Thread(() => { SendMessage(data); });
                    thread.Name = i.ToString();
                    listOfThreads.Add(thread);
                }
         }

        private static void StartThreads(List<Thread> lstThreads)
        {
            foreach (Thread th in lstThreads)
            {
                th.Start();
            }  
        }
        private static void SendMessage(string payload)
        {
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
            {
                EntityPath = EventHubName
            };

            eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            SendMessagesToEventHub(payload);

            eventHubClient.Close();
        }

        private static void SendMessagesToEventHub(string payload)
        {
            for (var i = 0; i < numberOfMsgs; i++)
            {
                try
                {
                    var message = $"Message: {payload}";
                    Console.WriteLine($"Thread {Thread.CurrentThread.Name} - Sending message {i + 1}");
                    eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
                }

                Task.Delay(interval);
            }
        }


Ali
  • 33
  • 1
  • 9

1 Answers1

0

I believe it is better to try fixing couple things in your code first and then focus why thread name is lost.

  1. Either create a dedicated EventHubClient for each thread or create it in the Main once. You are apperantly overriding the same client pointer each time you new up.

  2. Await SendAsync call, currently your approach is fire and forget and I really don't recommend that. Consider converting all your stack to async.

  3. If order of events is important then consider using PartitionSender.

Serkant Karaca
  • 1,896
  • 9
  • 8