代码没有从类方法执行

时间:2015-03-25 17:46:41

标签: c# windows-runtime windows-phone-8.1 async-await win-universal-app

我有一个有趣的问题...对于我的Windows Phone 8.1通用应用程序,我从我的代码中调用了我的类中定义的方法(CommAuthState):

这是调用此方法的截断代码。

    public async void ShowInitialPosts(object sender, RoutedEventArgs e)
        {

#if WINDOWS_PHONE_APP
            Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#endif

            //Get reference to the App setting container...
            Windows.Storage.ApplicationDataContainer appRoamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

            //Get the value for the logged in state and remembering option.... 
            string commLoggedInValue = (string)appRoamingSettings.Values["CommLoggedIn"];

            //If not logged in, redirect to the Community sign in page...


            if (commLoggedInValue != "Yes")
            {
                this.Frame.Navigate(typeof(CommSignIn));
            }

            else if (commLoggedInValue == "Yes")
            {

               await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    //Check the access token and its validity...
                    forum_Hepler.CommAuthState(errorMessage, pgbar, pgText, ServerNetworkError);

                });

                //Get the access token value...
                string myAccessTokenValue = (string)appRoamingSettings.Values["MyAccessToken"];

                //Set the access token to the page variable... 
                accesstoken = myAccessTokenValue;


                // Show the progress bar
                mycontrols.progressbarShow(pgbar, pgText);

                //Set the initial forum URL and page index..
                downloadedPostsIndex = 0;
                forumUrl = forumUrl + downloadedPostsIndex;

                // Make a REST API call with Oauth token........
                string telligentResult = await forum_Hepler.MyForumPostsOauth(forumUrl, accesstoken, errorMessage);


          .....
          .......

   } 

这是我的班级方法:

   public async void CommAuthState(string errormessage, ProgressBar myprogressbar, TextBlock mytextblock, TextBlock myservernetworkerror) {
     // Start showing the progress bar...      
     mycontrols.progressbarShow(myprogressbar, mytextblock);

     //Get the access token value...
     string myAccessTokenValue = (string) appRoamingSettings.Values["MyAccessToken"];

     //Get the refresh token value...
     string myRefreshTokenValue = (string) appRoamingSettings.Values["MyRefreshToken"];

     //Get the original access token obtain time....
     long myAccessTokenObtainedTimeValue = (long) appRoamingSettings.Values["MyAccessTokenObtainedTime"];

     //Convertig date/time back to DateTime object....
     origAccessTokenObtainedTime = DateTime.FromBinary(myAccessTokenObtainedTimeValue);

     currentDateTime = DateTime.Now;

     //Check to see if access token has expired....
     accessTokenTimeElasped = currentDateTime - origAccessTokenObtainedTime;
     accessTokenTimeElapsedSecs = accessTokenTimeElasped.TotalSeconds;

     //Get the value of the access token expiration....
     int MyAccessTokenExpiresValue = (int) appRoamingSettings.Values["MyAccessTokenExpires"];

     if (accessTokenTimeElapsedSecs <= MyAccessTokenExpiresValue) {

       //Get the long GUID value to be used for the GetOauthStuff function below...
       string myLongGuidValue = (string) appRoamingSettings.Values["MyLongGuid"];

       //Make a GET call to the OAUTH endpoint to get another Access Token by sending the refresh token ....
       // string telligentOauthResult = await GetOauthStuff(oauthEndPoint, MyLongGuidValue, keyName, keySecret, errormessage);

       string telligentOauthResult = await GetRefreshedOauthStuff(oauthEndPoint, myLongGuidValue, myRefreshTokenValue, keyName, keySecret, errormessage);


       if (telligentOauthResult != null) {
         // Creating a list out of the JSON object returned by the Telligent API endpoint...
         ForumHelper.OAuthObject mytelligentResult = JsonConvert.DeserializeObject < ForumHelper.OAuthObject > (telligentOauthResult);

         var accessToken = mytelligentResult.OAuthToken.access_token;

         // Get the access token and the time and save it to settings
         accessTokenObtainedTime = DateTime.Now;

         var accessTokenError = mytelligentResult.OAuthToken.error;
         var accessTokenTime = mytelligentResult.OAuthToken.expires_in;
         var refreshToken = mytelligentResult.OAuthToken.refresh_token;


         //Save access token to the app settings...
         appRoamingSettings.Values["MyAccessToken"] = accessToken;

         //Converting to binary format before saving since app settings cannot save in DateTime format and also we can convert it back later to the DateTime object
         appRoamingSettings.Values["MyAccessTokenObtainedTime"] = accessTokenObtainedTime.ToBinary();
       } else {
         // Stop showing the progress bar...
         mycontrols.progressbarNoShow(myprogressbar, mytextblock);

         //Show the error message...
         myservernetworkerror.Visibility = Windows.UI.Xaml.Visibility.Visible;
       }
     }
   }

一切正常,我可以逐步完成代码,看看它是如何运作的,直到我进入GetRefreshedOauthStuff方法。这里是GetRefreshedOauthStuff方法供参考:

     public async Task < string > GetRefreshedOauthStuff(string url, string MyGUID, string MyResfreshToken, string KeyName, string KeySecret, string ErrorMessage) {
       //Setting up Httpclient to send to the Telligent API call..... 
       var client = new System.Net.Http.HttpClient();

       var adminKey = String.Format("{0}:{1}", KeySecret, KeyName);
       var adminKeyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(adminKey));

       // Send customized headers with the token  and impersonation request 
       client.DefaultRequestHeaders.Add("Rest-User-Token", adminKeyBase64);
       client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

       //Adding the long GUID to the OAUTH endpoint URL...
       url = url + MyGUID + "&refresh_token=" + MyResfreshToken;

       //For getting the list of posts....
       System.Net.Http.HttpResponseMessage telligentResponse = await client.GetAsync(url);


       if (telligentResponse.StatusCode == System.Net.HttpStatusCode.OK || telligentResponse.StatusCode == System.Net.HttpStatusCode.Forbidden) {
         // Read the HTTP response content....
         HttpContent responseContent = telligentResponse.Content;

         // Read the response content as string.....
         return await responseContent.ReadAsStringAsync();
       } else {
         throw new Exception("Error connecting to " + url + " ! Status: " + telligentResponse.StatusCode);

         //Pop up the server or network issue message...
         //mycontrols.popupMessages(ErrorMessage, "Network or Server error!");

         ////Navigate back to the main page....
         //this.rootFrame.Navigate(typeof(MainPage));
         //return null;
       }
     }

我的代码一执行此行:

System.Net.Http.HttpResponseMessage telligentResponse = await client.GetAsync(url);

它退出此方法而不是完全完成它并在我的启动方法ShowInitialPosts中转到此行:

 string telligentResult = await forum_Hepler.MyForumPostsOauth(forumUrl, accesstoken, errorMessage);

这显然会产生问题并导致我的逻辑失败。我在这做错了什么?我该如何解决这个问题?

非常感谢任何帮助或指示 感谢

1 个答案:

答案 0 :(得分:0)

这正是await应该做的事情。它不会阻止线程执行 - 它告诉方法将控制权返回给调用它的人,然后在async方法完成后继续执行。

Eric Lippert有一篇很棒的博客文章。 http://blogs.msdn.com/b/ericlippert/archive/2010/10/29/asynchronous-programming-in-c-5-0-part-two-whence-await.aspx