title: Getting InvalidOperationException during call to GetResponseAsync()?
body: <p><em>PREFACE: I know the code excerpt is lengthy but I did't want to leave out a detail that someone else might spot as the cause of the issue.  The reason for the somewhat verbose nature of the code and the many Exception traps is due to the hunt for the <strong>NullReferenceException</strong> that I describe below.  You can wade through the code quickly to the salient parts by jumping to the <strong>await</strong> keywords found amongst the <strong>async</strong> methods that call each other.</em></p>
  
  <p><em>UPDATE: The InvalidOperationException is occurring because I am altering the IsEnabled status of certain buttons.  I am on the Main thread so I am not sure why this is happening.  Does anyone know why?</em></p>
  
  <p>I have a Windows Phone 7 application written C# that is getting a <strong>System.InvalidOperationException</strong> when <strong>GetResponseAsync()</strong> is called in a particular code context.  The application uses the PetFinder API to create a Cat Breed Guessing game with the intention of helping cats in animal shelters get adopted.  Here is the exact Exception message in its entirety:</p>
  
  <pre><code>Message: An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.ni.dll
  </code></pre>
  
  <p>Before the Exception occurs, there are several successful calls to <strong>GetResponseAsync()</strong>.  I have included the code for the methods involved in the Exception in the order that they are called below.  Can someone tell me why I am getting this Exception and how to fix it?</p>
  
  <p>The Exception is occurring completely out of the current code context that calls it, so it's some interaction between the code below and the library that contains <strong>GetResponseAsync()</strong> that is creating the conditions for the problem.  The thread code context just before the call to <strong>GetResponseAsync()</strong> is the <strong>Main thread</strong>. </p>
  
  <p>BACKGROUND NOTE:  </p>
  
  <p>This all began while I was chasing down a NullReferenceException that was occuring during the call to <strong>getRandomPetExt()</strong> within <strong>doLoadRandomPet()</strong>.  From the reading I did on SO, my guess is that a <strong>NULL Task</strong> was being returned from <strong>getRandomPetExt()</strong>.  But if you look at that code you'll see I'm doing everything in my power to trap a spurious Exception and to avoid returning a NULL Task.  My current belief still at this time is that the NULL Task is occurring because some other code is generating a spurious Exception outside of my code.  Perhaps something in <strong>Microsoft.Bcl.Async</strong>?  Is this some strange synchronization context problem or hidden cross-thread access issue?</p>
  
  <p>The strange part is that before I made a particular change I did not get the <strong>InvalidOperationException</strong> at all, only the intermittent <strong>NullReferenceException</strong> every 1 out of 20 to 30 calls to the method chain shown below.  The <strong>InvalidOperationException</strong> on the other hand <strong>happens every time</strong> with the new code structure.  The change I made was to me a minor one meant to help my debugging efforts.  The only thing I did was create a method wrapper that moved the guts of <strong>loadRandomPet()</strong> into <strong>doLoadRandomPet()</strong>.  I did this so I could disable some buttons that triggered method calls that might interfere with the operation to get a random pet.  I wrapped the call to <strong>doLoadRandomPet()</strong> in a try/finally block, to make sure the buttons were re-enabled when the operation exited.  Why would this cause such a major change in code execution?</p>
  
  <pre><code>    async private void loadRandomPet(int maxRetries = 3)
      {
          // Do not allow the Guess My Breed or Adopt Me buttons to be 
          //  clicked while we are getting the next pet.
          btnAdoptMe.IsEnabled = false;
          btnGuessMyBreed.IsEnabled = false;
  
          try
          {
              await doLoadRandomPet(maxRetries);
          }
          finally
          {
      // &gt;&gt;&gt;&gt;&gt; THIS CODE IS NEVER REACHED.
  
              // Make sure the buttons are re-enabled.
              btnAdoptMe.IsEnabled = true;
              btnGuessMyBreed.IsEnabled = true;
          }
      }
  
      // -------------------- CALLED NEXT
  
      /// &lt;summary&gt;
      /// (awaitable) Loads a random pet with a limit on the number of retries in case of failure.
      /// &lt;/summary&gt;
      /// &lt;param name="maxRetries"&gt;The number of retries permitted.&lt;/param&gt;
      async private Task doLoadRandomPet(int maxRetries = 3)
      {
          // Show the busy indicator.
          radbusyMain.Visibility = Visibility.Visible;
  
          try
          {
  
              // Get a random pet.
              List&lt;KeyValuePair&lt;string, string&gt;&gt; listUrlArgs = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
  
              // Only cats.
              listUrlArgs.addKVP("animal", PetFinderUtils.EnumAnimalType.cat.ToString());
  
              if (!String.IsNullOrWhiteSpace(MainMenu.ZipCode))
              {
                  listUrlArgs.addKVP(PetFinderUtils.URL_FIELD_LOCATION, MainMenu.ZipCode);
              }
  
              if (maxRetries &lt; 0)
                  throw new ArgumentOutOfRangeException("The maximum retries value is negative.");
  
              Debug.WriteLine("------------------ START: LOADING Random Pet ----------------");
  
              // Loop until a random pet is found.
              int numRetries = 0;
  
              // Select the breed, otherwise we will get a ton of "Domestic Short Hair" responses,
              //  which are not good for the game.  Breeds that are returning empty search
              //  results this session are filtered too.
              string strBreedName = MainMenu.GetRandomBreedName();
  
              listUrlArgs.addKVP("breed", strBreedName);
  
              while (numRetries &lt;= maxRetries)
              {
                  try
                  {
                      // Save the last successful retrieval.
                      if (this._pbi != null)
                          _pbiLast = this._pbi;
  
                      this._pbi = await getRandomPetExt(listUrlArgs);
                  }
                  catch (EmptySearchResultsException esr)
                  {
                      // getRandomPetExt() could not find a suitable cat given the current parameters.
                      //  Swallow the Exception without notifying the user.  Just allow the code
                      //  further down to re-use the last cat retrieved in the hopes the next
                      //  quiz won't have the problem.  
                      Debug.WriteLine("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; doLoadRandomPet() - getRandomPet() failed to find a cat.");
                  }
                  catch (PetFinderApiException pfExc)
                  {
                      if (pfExc.ResponseCode == PetFinderUtils.EnumResponseCodes.PFAPI_ERR_LIMIT)
                          // Swallow the Exception, but let the user know to stop playing for the awhile
                          //  since we have exceeded our rate limit.
                          CatQuizAux.EasyToast("The PetFinder server is busy.\nPlease try playing the game\nlater.");
                      else
                          // Swallow the Exception, but let the user know to stop playing for the awhile
                          //  since we have exceeded our rate limit.
                          CatQuizAux.EasyToast("The PetFinder may be down.\nPlease try playing the game\nlater.");
  
                      // Just exit.
                      return;
                  } // try
                  catch (Exception exc)
                  {
                      // This is really bad practice but we're out of time.   Just swallow the Exception
                      //  to avoid crashing the program.
                      Debug.WriteLine("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; doLoadRandomPet() - getRandomPet() Other Exception occurrred.  Exception Message: " + exc.Message);
                  }
  
  
                  // If the returned pet is NULL then no pets using the current search criteria
                  //  could be found.
                  if (this._pbi != null)
                  {
                      // Got a random pet, stop looping.  Save it to the backup cat field too.
                      break;
                  }
                  else
                  {
                      // Are we using a location?
                      if (listUrlArgs.hasKey(PetFinderUtils.URL_FIELD_LOCATION))
                          // Retry without the location to open the search to the entire PetFinder API
                          //  inventory.
                          listUrlArgs.deleteKVP(PetFinderUtils.URL_FIELD_LOCATION);
                      else
                      {
                          // Use a differet breed.  Add the current breed to the list of breeds returning
                          //  empty search results so we don't bother with that breed again this session.
                          MainMenu.ListEmptyBreeds.Add(strBreedName);
  
                          // Remove the current breed.
                          listUrlArgs.deleteKVP("breed");
  
                          // Choose a new breed.
                          strBreedName = MainMenu.GetRandomBreedName();
                          listUrlArgs.addKVP("breed", strBreedName);
                      } // else - if (listUrlArgs.hasKey(PetFinderUtils.URL_FIELD_LOCATION))
                  } // if (this._pbi == null)
  
                  // Sleep a bit.
                  await TaskEx.Delay(1000);
  
                  numRetries++;
              } // while (numRetries &lt;= maxRetries)
  
              // If we still have a null _pbi reference, use the back-up one.
              if (this._pbi == null)
                  this._pbi = this._pbiLast;
  
              if (this._pbi == null)
                  throw new ArgumentNullException("(ViewPetRecord::doLoadRandomPet) Failed completely to find a new cat for the quiz.  Please try again later.");
  
              // Add the pet to the already quizzed list.
              MainMenu.AddCatQuizzed(this._pbi.Id.T.ToString());
  
              // Show the cat's details.
              lblPetName.Text = this._pbi.Name.T;
              imgPet.Source = new BitmapImage(new Uri(this._pbi.Media.Photos.Photo[0].T, UriKind.Absolute));
  
              // Dump the cat's breed list to the Debug window for inspection.
              dumpBreedsForPet(this._pbi);
          }
          finally
          {
              // Make sure the busy indicator is hidden.
              radbusyMain.Visibility = Visibility.Collapsed;
          }
      } // async private void doLoadRandomPet(int maxRetries = 3)
  
      // -------------------- CALLED NEXT
  
      /// &lt;summary&gt;
      /// Gets a Random Pet.  Retries up to maxRetries times to find a pet not in the already &lt;br /&gt;
      ///  quizzed list before giving up and returning the last one found.  Also skips pets without &lt;br /&gt;
      ///  photos.
      /// &lt;/summary&gt;
      /// &lt;param name="listUrlArgs"&gt;A list of URL arguments to pass add to the API call.&lt;/param&gt;
      /// &lt;param name="maxRetries"&gt;The number of retries to make.&lt;/param&gt;
      /// &lt;returns&gt;The basic info for the retrieved pet or NULL if a pet could not be found &lt;br /&gt;
      ///  using the current URL arguments (search criteria).&lt;/returns&gt;
      async private Task&lt;PetBasicInfo&gt; getRandomPetExt(List&lt;KeyValuePair&lt;string, string&gt;&gt; listUrlArgs, int maxRetries = 3)
      {
          PetBasicInfo newPbi = null;
  
          try
          {
              newPbi = await doGetRandomPetExt(listUrlArgs, maxRetries);
          }
          catch (Exception exc)
          {
              Debug.WriteLine("&gt;&gt;&gt;&gt;&gt;&gt; (ViewPetRecord::getRandomPetExt) EXCEPTION: " + exc.Message);
              throw;
          } // try/catch
  
          return newPbi;
      } // async private void getRandomPetExt()
  
      // -------------------- CALLED NEXT
  
      // This was done just to help debug the NullReferenceException error we are currently fighting.
      //  see getRandomPetExt() below.
      async private Task&lt;PetBasicInfo&gt; doGetRandomPetExt(List&lt;KeyValuePair&lt;string, string&gt;&gt; listUrlArgs, int maxRetries = 3)
      {
          if (maxRetries &lt; 0)
              throw new ArgumentOutOfRangeException("The maximum retries value is negative.");
  
          Debug.WriteLine("------------------ START: Getting Random Pet ----------------");
  
          // Loop until a random pet is found that has not already been used in the quiz or until
          //  we hit the maxRetries limit.
          int numRetries = 0;
  
          PetBasicInfo pbi = null;
  
          while (numRetries &lt;= maxRetries)
          {
              try
              {
                  pbi = await MainMenu.PetFinderAPI.GetRandomPet_basic(listUrlArgs);
              }
              catch (PetFinderApiException pfExcept)
              {
                  // pfExcept.ResponseCode = PetFinderUtils.EnumResponseCodes.PFAPI_ERR_LIMIT;
  
                  switch (pfExcept.ResponseCode)
                  {
                      case PetFinderUtils.EnumResponseCodes.PFAPI_ERR_NOENT:
                          Debug.WriteLine("The PetFinder API returned an empty result set with the current URL arguments.");
                          // No results found.  Swallow the Exception and return
                          //  NULL to let the caller know this.
                          return null;
                      case PetFinderUtils.EnumResponseCodes.PFAPI_ERR_LIMIT:
                          Debug.WriteLine("The PetFinder API returned a rate limit error.");
                          // Throw the Exception.  Let the caller handler it.
                          throw;
                      default:
                          // Rethrow the Exception so we know about it from the crash reports.
                          // Other Exception.  Stop retrying and show the user the error message.
                          Debug.WriteLine("Exception during getRandomPetExt()\n" + pfExcept.ErrorMessage);
                          throw;
                  } // switch()
              }
  
              // Does the pet have a photo?
              if (pbi.Media.Photos.Photo.Length &gt; 0)
              {
                  // Yes. Has the pet already been used in a quiz?
                  if (!MainMenu.IsCatQuizzed(pbi.Id.T.ToString()))
                      // No. Success.
                      return pbi;
              } // if (pbi.Media.Photos.Photo.Length &gt; 0)
  
              // Retry required.
              Debug.WriteLine(String.Format("Retrying, retry count: {0}", numRetries));
  
              // No photo or already used in a quiz.  Wait a little before retrying.
              await TaskEx.Delay(1000);
  
              // Count retires.
              numRetries++;
          } // while (numRetries &lt;= maxRetries)
  
          // Unable to find a cat not already quizzed.  Just return the last retrieved.
          Debug.WriteLine("Retry count exceeded.  Returning last retreived pet.");
  
          // Returning NULL results in a await throwing a non-specific NullReferenceException.  
          //  Better to throw our own Exception.
          throw new EmptySearchResultsException("(ViewPetRecord::getRandomPetExt) Unable to retrieve a new random cat from the PetFinder API server.");
          // return pbi;
      } // async private PetBasicInfo doGetRandomPetExt()
  
      // ------------------ CALLED NEXT
  
      /// &lt;summary&gt;
      /// Returns the basic information for a randomly chosen pet of the given animal type.
      /// &lt;/summary&gt;
      /// &lt;param name="enAnimalType"&gt;The desired animal type to restrict the search to.&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      async public Task&lt;JSON.JsonPetRecordTypes.PetBasicInfo&gt; GetRandomPet_basic(List&lt;KeyValuePair&lt;string, string&gt;&gt; urlArgumentPairs = null)
      {
          Debug.WriteLine("(GetRandomPet_basic) Top of call.");
  
          // If the URL Argument Pairs parameter is null, then create one.
          if (urlArgumentPairs == null)
              urlArgumentPairs = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
  
          // Add the "output" parameter that tells PetFinder we want the Basic information for the pet,
          //  not the ID or full record.
          urlArgumentPairs.addKVP("output", "basic");
  
          // Add a unique URL argument to defeat URL caching that may be taking
          //  place in the Windows Phone library or at the PetFinder API server.
          //  This defeats the problem so that a new random pet is returned
          //  each call, instead of the same one.
          long n = DateTime.Now.Ticks;
  
          urlArgumentPairs.addKVP("nocache", n.ToString());
  
          // Build the API call.
          string strApiCall =
                  buildPetFinderApiUrl(METHOD_RANDOM_PET,
                  urlArgumentPairs);
  
          Debug.WriteLine("(GetRandomPet_basic) URL for call: \n" + strApiCall);
  
          // Make the call.
          string strJsonReturn = await Misc.URLToStringAsyncEZ(strApiCall);
  
          bool bIsJsonReturnValid = false;
  
          try
          {
              JSON.JsonPetRecordTypes.PetRecordBasicInfo jsonPetBasic = JsonConvert.DeserializeObject&lt;JSON.JsonPetRecordTypes.PetRecordBasicInfo&gt;(strJsonReturn);
  
              // Deserialization succeeded.
              bIsJsonReturnValid = true;
  
              // Success code?
              // For some strange reason T is cast to an "int" here where in GetBreedList it's equivalent is cast to a string.
              int iResponseCode = jsonPetBasic.Petfinder.Header.Status.Code.T;
  
              if (iResponseCode != 100)
                  throw new PetFinderApiException("PetFinder::GetRandomPet_basic", iResponseCode);
                  // throw new Exception("(PetFinder::GetRandomPet_basic) The response document contains a failure response code: " + iResponseCode.ToString() + ":" + jsonPetBasic.Petfinder.Header.Status.Message);
  
              // Return the pet record basic info.
              return jsonPetBasic.Petfinder.Pet;
          }
          finally
          {
              if (!bIsJsonReturnValid)
                  // Setting debug trap to inspect JSON return.
                  Debug.WriteLine("JSON Deserialization failure.");
  
              Debug.WriteLine("(GetRandomPet_basic) BOTTOM of call.");
          } // try/finally
      }
  
      // -------------------- CALLED NEXT, never returns
  
      /// &lt;summary&gt;
      /// (awaitable) Simpler version of above call.  Same warnings about getting byte stream &lt;br /&gt;
      ///  objects apply here as they do to URLtoStringAsync()
      /// &lt;/summary&gt;
      /// &lt;param name="stUrl"&gt;&lt;/param&gt;
      /// &lt;param name="reqMethod"&gt;&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      async public static Task&lt;string&gt; URLToStringAsyncEZ(string strUrl, HttpRequestMethod reqMethod = HttpRequestMethod.HTTP_get)
      {
          strUrl = strUrl.Trim();
  
          if (String.IsNullOrWhiteSpace(strUrl))
              throw new ArgumentException("(Misc::URLToStringAsyncEZ) The URL is empty.");
  
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
  
          // Get the string value for the request method.
          request.Method = reqMethod.GetDescription();
  
      // &gt;&gt;&gt;&gt;&gt; THIS CALL to GetResponseAsync() TRIGGERS THE EXCEPTION (see stack trace below)
          // Async wait for the respone.
          HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
  
          // Use a stream reader to return the string.
          using (var sr = new StreamReader(response.GetResponseStream()))
          {
              return sr.ReadToEnd();
          }
      }
  
  // -------------------- STACK TRACE JUST BEFORE URLToStringAsync(), the call the triggers the exception.
  
  &gt;   Common_WP7.DLL!Common_WP7.Misc.URLToStringAsyncEZ(string strUrl, Common_WP7.Misc.HttpRequestMethod reqMethod) Line 1079 C#
  CatQuiz.DLL!CatQuiz.PetFinderUtils.GetRandomPet_basic(System.Collections.Generic.List&lt;System.Collections.Generic.KeyValuePair&lt;string,string&gt;&gt; urlArgumentPairs) Line 441    C#
  CatQuiz.DLL!CatQuiz.ViewPetRecord.doGetRandomPetExt(System.Collections.Generic.List&lt;System.Collections.Generic.KeyValuePair&lt;string,string&gt;&gt; listUrlArgs, int maxRetries) Line 55    C#
  CatQuiz.DLL!CatQuiz.ViewPetRecord.getRandomPetExt(System.Collections.Generic.List&lt;System.Collections.Generic.KeyValuePair&lt;string,string&gt;&gt; listUrlArgs, int maxRetries) Line 123 C#
  CatQuiz.DLL!CatQuiz.ViewPetRecord.doLoadRandomPet(int maxRetries) Line 243  C#
  CatQuiz.DLL!CatQuiz.ViewPetRecord.loadRandomPet(int maxRetries) Line 343    C#
  CatQuiz.DLL!CatQuiz.ViewPetRecord.PageViewPetRecord_Loaded(object sender, System.Windows.RoutedEventArgs e) Line 355    C#
  System.Windows.ni.dll!MS.Internal.CoreInvokeHandler.InvokeEventHandler(int typeIndex, System.Delegate handlerDelegate, object sender, object args)  Unknown
  System.Windows.ni.dll!MS.Internal.JoltHelper.FireEvent(System.IntPtr unmanagedObj, System.IntPtr unmanagedObjArgs, int argsTypeIndex, int actualArgsTypeIndex, string eventName)    Unknown
  
      ======================= EXCEPTION
  
  // -------------------- STACK TRACE when EXCEPTION occurs
  &gt;   CatQuiz.DLL!CatQuiz.App.Application_UnhandledException(object sender, System.Windows.ApplicationUnhandledExceptionEventArgs e) Line 101 C#
  System.Windows.ni.dll!MS.Internal.Error.CallApplicationUEHandler(System.Exception e)    Unknown
  System.Windows.ni.dll!MS.Internal.Error.IsNonRecoverableUserException(System.Exception ex, out uint xresultValue)   Unknown
  System.Windows.ni.dll!MS.Internal.JoltHelper.FireEvent(System.IntPtr unmanagedObj, System.IntPtr unmanagedObjArgs, int argsTypeIndex, int actualArgsTypeIndex, string eventName)    Unknown
  
  
      // -------------------- CODE CONTEXT when EXCEPTION occurs
      // Code to execute on Unhandled Exceptions
      private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
      {
          if (System.Diagnostics.Debugger.IsAttached)
          {
              // An unhandled exception has occurred; break into the debugger
              System.Diagnostics.Debugger.Break();
          }
      }
  </code></pre>