title: Silverlight - Waiting for asynchronous call to finish before returning from a method
body: <p>I have a Silverlight application that uses WCF services and also uses the Wintellect Power Threading library to ensure logic executes fully before the application continues.  This is achieved by calling back to the application using delegates so it can continue after the service call has completely finished.</p>
  
  <p>I wish to achieve the same thing in another part of my application but without the use of callbacks e.g. call method that uses WCF service to say load an object from the database, wait for this to return and then return the Id of the object from the original method called.</p>
  
  <p>The only way I could see to do this was to carry out the call to the WCF service in a helper library which loads the object on a different thread and the original method would keep checking the helper library (using static variables) to wait for it to complete and then return it.</p>
  
  <p>Is this the best way to achieve this functionality?  If so here are details of my implementation which is not working correctly.</p>
  
  <pre><code>public class MyHelper
  {
  
      private static Thread _thread;
      private static User _loadedObject;        
  
      public static GetUser()
      {
          return _loadedObject;
      }
  
      public static void LoadObject(int userId)
      {
          _loadedObject = null;
          ParameterizedThreadStart ts = new ParameterizedThreadStart(DoWork);           
          _thread = new Thread(ts);
          _thread.Start(userId);
  
      }
  
      private static void DoWork(object parameter)
      {            
          var ae = new AsyncEnumerator();
          ae.BeginExecute(DoWorkWorker(ae, Convert.ToInt32(parameter)), ae.EndExecute);    
      }
  
      private static IEnumerator&lt;Int32&gt; DoWorkWorker(AsyncEnumerator ae, int userId)
      {
          // Create a service using a helper method
          var service = ServiceHelper.GetService&lt;IUserServiceAsync&gt;();
          service.BeginGetUserById(userId, ae.End(), null);
          yield return 1;
  
          _loadedObject = service.EndGetUserById(ae.DequeueAsyncResult());
          _thread.Abort();
      }
  }
  </code></pre>
  
  <p>My method then is:</p>
  
  <pre><code>public int GetUser(int userId)
  {
      MyHelper.LoadObject(userId);
      User user = MyHelper.GetUser();
      while (user == null)
      {
          Thread.Sleep(1000);
          user = MyHelper.GetUser();
      }
      return user.Id;
   }
  </code></pre>
  
  <p>The call to the get the user is executed on a different thread in the helper method but never returns.  Perhaps this is due to the yield and the calling method sleeping.  I have checked the call to get the user is on a different thread so I think everything should be kept separate,</p>