title: Asynchronous waiting while C# function is executing
body: <p>I have a blocking function that executes an asynchronous MySQL query and returns the result when it is obtained. The reason is is asynchronous is this program is not allowed to lock up during a query.</p>
  
  <p>The function is called when the user presses a button, so the function may get called several times before the first query completes. I thought I could add a boolean to check whether or not a query is executing and have the function wait until it's done before continuing, but it is not working as intended. There is some issue with the two DoEvents() I use. If you comment out either one, it runs just fine, except the UI freezes.</p>
  
  <p>How can I make the function do a non-blocking wait while a query is executing, as well as do a non-blocking wait while the query itself is being fetched? I would really prefer to keep this on one thread, as the function itself is blocking to the code that called it. Any help would b e greatly appreciated!</p>
  
  <pre><code>    public Exception LastError;
      public MySqlConnection Conn;
      public MySqlDataReader Reader;
      public bool IsExecuting = false;
  
      public MySqlDataReader MySQL_Query(string Query, [Optional] params string[] Values)
      {
          while (IsExecuting)
          {
              System.Windows.Forms.Application.DoEvents();
              System.Threading.Thread.Sleep(20);
          }
  
          if (IsConnected() == false)
              ConnectToDatabase();
  
          for (int i = 0; i &lt; Values.Length; i++)
              Values[i] = MySQL_SafeValue(Values[i]);
          if (Reader != null &amp;&amp; Reader.IsClosed == false)
              Reader.Close();
  
          IsExecuting = true;
          try
          {
              MySqlCommand Cmd = new MySqlCommand(String.Format(Query, Values), Conn);
              IAsyncResult aRes = Cmd.BeginExecuteReader();
              while (!aRes.IsCompleted)
              {
                  System.Windows.Forms.Application.DoEvents();
                  System.Threading.Thread.Sleep(20);
              }
              Reader = Cmd.EndExecuteReader(aRes);
              IsExecuting = false;
          }
          catch (Exception e)
          {
              IsExecuting = false;
              LastError = e;
              return null;
          }
  
          return Reader;
      }
  </code></pre>