title: How to ensure order of async operation calls?
body: <p>[This <strong>appears</strong> to be a loooong question but I have tried to make it as clear as possible. Please have patience and help me...]</p>
  
  <p>I have written a test class which supports an Async operation. That operation does nothing but reports 4 numbers:</p>
  
  <pre><code>class AsyncDemoUsingAsyncOperations
  {
      AsyncOperation asyncOp;
      bool isBusy;
  
      void NotifyStarted () {
          isBusy = true;
          Started (this, new EventArgs ());
      }
  
      void NotifyStopped () {
          isBusy = false;
          Stopped (this, new EventArgs ());
      }
  
      public void Start () {
          if (isBusy)
              throw new InvalidOperationException ("Already working you moron...");
  
          asyncOp = AsyncOperationManager.CreateOperation (null);
          ThreadPool.QueueUserWorkItem (new WaitCallback (StartOperation));
      }
  
      public event EventHandler Started = delegate { };
      public event EventHandler Stopped = delegate { };
      public event EventHandler&lt;NewNumberEventArgs&gt; NewNumber = delegate { };
  
      private void StartOperation (object state) {
          asyncOp.Post (args =&gt; NotifyStarted (), null);
  
          for (int i = 1; i &lt; 5; i++)
              asyncOp.Post (args =&gt; NewNumber (this, args as NewNumberEventArgs), new NewNumberEventArgs (i));
  
          asyncOp.Post (args =&gt; NotifyStopped (), null);
      }
  }
  
  class NewNumberEventArgs: EventArgs
  {
      public int Num { get; private set; }
  
      public NewNumberEventArgs (int num) {
          Num = num;
      }
  }
  </code></pre>
  
  <p>Then I wrote 2 test programs; one as console app and another as windows form app. Windows form app works as expected when I call Start repeatedly:</p>
  
  <p><a href="https://i.stack.imgur.com/qAaK0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qAaK0.png" alt="alt text"></a>
  </p>
  
  <p>But console app has hard time ensuring the order:</p>
  
  <p><a href="https://i.stack.imgur.com/4td3b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4td3b.png" alt="alt text"></a>
  </p>
  
  <p>Since I am working on class library, I have to ensure that my library works correctly in all app models (Haven't tested in ASP.NET app yet). So I have following questions:</p>
  
  <ol>
  <li>I have tested enough times and it appears to be working but is it OK to assume above code will always work in windows form app?</li>
  <li>Whats the reason it (order) doesn't work correctly in console app? How can I fix it?</li>
  <li>Not much experienced with ASP.NET. Will the order work in ASP.NET app?</li>
  </ol>
  
  <p>[EDIT: Test stubs can be seen <a href="http://dl.dropbox.com/u/2731573/AsyncTestStubs.cs" rel="nofollow noreferrer">here</a> if that helps.]</p>