title: Avoid Application.DoEvents() in C#
body: <p>A lot of good programmers (including a lot of good members of Stackoverflow) are against using <code>Application.DoEvents()</code> whatever the circumstances are. Actually it is even supported with plenty of articles in the net, like <a href="http://blogs.msdn.com/b/jfoscoding/archive/2005/08/06/448560.aspx" rel="nofollow noreferrer">this one</a>, <a href="https://stackoverflow.com/questions/5181777/use-of-application-doevents">this famous debate on SO</a>, ...</p>
  
  <p>Though, I'm stuck in a case, where (I) think <code>DoEvents()</code> is the unique exit (lack of experience). That's enough as introduction, let's see some coding.</p>
  
  <p>I have a 'serialPort' component to connect with a controller through serial communication, send command and wait for its response, that's all.</p>
  
  <pre><code>string response = "";
  bool respFlag;
  
  private string sendCommand(string command)
  {
    respFlag = false;  //initialize respFlag
  
    serialPort1.Write(command);  // send the command
  
    Stopwatch timer = Stopwatch.StartNew(); // start a timer
    while(true)
    {
      // break from the loop if receive a response
      if(respFlag) break;  
  
      // timeOut error if no response for more than 500msec
      if(timer.ElapsedMilliseconds &gt;= 500) break;
  
      // here comes the UGLY part
      Application.DoEvents(); 
    }
  
     return response;
  }
  </code></pre>
  
  <p>in DataReceived method of my serialPort, I read the existing response and break the loop</p>
  
  <pre><code>private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  {
    response = serialPort1.ReadExisting();
  
    // set the flag to true to exit the infinite loop in sendCommand
    respFlag = true; 
  }
  </code></pre>
  
  <p>It's not exactly like this, but this is a sample code that shows how I sned-receive via serial communication, would you kindly show me where am I forcing myself into this pitfall?</p>