title: Using Queue in C#?
body: <p>Ok, so I am working on a console application that pulls from an API every 3 seconds. The API returns a list of "Messages" that I would need to add to a queue and have something in the background constantly checking for new items in the queue, looping through the items, the doing something with the items.</p>
  
  <p><strong>Here is what I have so far:</strong>
  Main Program Method</p>
  
  <pre><code>static void Main(string[] args)
  {
      ConsoleKeyInfo answer = Console.ReadKey(true);
      if (answer.Key == ConsoleKey.Y)
      {
          while (true)
          {
              foreach (MessageObject message in messageQueue)
              {
                  SendCommand(message.Message);
  
                  // Debug
                  Console.WriteLine(message.Message);
                  messageQueue.Dequeue();
              }
          }
      }
      else
      {
          Environment.Exit(0);
      }
  }
  </code></pre>
  
  <p>CheckChat Method</p>
  
  <pre><code>static private async void CheckChat()
  {
      Chat chat = await ChatAPI.GetChat(428);
  
      foreach (MessageObject chatMessage in chat.Messages)
      {
          messageQueue.Enqueue(chatMessage);
      }
  }
  </code></pre>
  
  <p>However, i get the following error: </p>
  
  <p><code>An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll</code></p>
  
  <p><code>Additional information: Collection was modified after the enumerator was instantiated.</code></p>
  
  <p>I understand that I am adding items to the list while looping through the queue, but how would I continuously check items in queue in the background as im adding objects?</p>