1

I have a BlockingCollection to which a string is added every 25ms. There is a thread(ProducerConsumer()) for consuming the collection. This is running on a windows service. The GetConsumingEnumerable on the ProducerConsumer() thread stops consuming the strings from the collection increasing the memory size of the collection.

Below is the code, it would be great if anyone can find the flaw in the code. Thanks in advance.

public delegate void EventHandler(string message);
 public event EventHandler OnEvent;

 private BlockingCollection<string> m_blockingCollection;

 //This method is called every 25ms
 private void Add(string msg)
 {
    m_blockingCollection.Add(msg);
 }
 //This is called on the service start 
 private void StartThread()
 {
    m_blockingCollection = new BlockingCollection<string>();
    System.Threading.Thread t = new System.Threading.Thread(ProducerConsumer)
    {
       IsBackground = true
    };
    t.Start();
 }
 private void ProducerConsumer()
 {
    try
      {
         foreach (var telegram in m_blockingCollection.GetConsumingEnumerable())
          {
             try
              {
                OnEvent?.Invoke(telegram);
              }
              catch (Exception ex)
              {
                 LogError(ex);
              }
          }
      }
      catch (Exception ex)
      {
         LogError(ex);
      }
      finally
      {
         LogWarning("Exiting producer consumer");
      }
 } 

I have taken a dump of the process and ran it on dotmemory, that showed that the highest memory is consumed by the blocking collection. However, There is no evidence from the windows event log viewer or my application logs that explains why this thread stopped. Restarting the service is fixing this problem for few days and again the same issue occurs.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104

0 Answers0