使用c#从异步方法分配全局变量

时间:2016-07-15 07:47:06

标签: c#

我有一个异步方法,我想拉一些数据并分配给全局变量以便在另一个方法中使用。 以下是方法:

private async void getgoogleplususerdataSer(string access_token)
    {
        try
        {
            HttpClient client = new HttpClient();
            var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;

            client.CancelPendingRequests();
            HttpResponseMessage output = await client.GetAsync(urlProfile);

            if (output.IsSuccessStatusCode)
            {
                string outputData = await output.Content.ReadAsStringAsync();
                GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);

                if (serStatus != null)
                {
                    gName = serStatus.name;
                    gEmail = serStatus.email;
                }
            }
        }
        catch (Exception ex)
        {
            //catching the exception
        }
    }

已经声明了变量gName和gEmail。 我想使用变量来使用以下逻辑注册用户:

 protected void RegisterGoogleUser()
    {
        string strCon = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        string sql5 = "SELECT Email FROM Members where Email=@gEmail";
        using (SqlConnection con5 = new SqlConnection(strCon))
        {
            using (SqlCommand cmd5 = new SqlCommand(sql5, con5))
            {
                con5.Open();
                cmd5.Parameters.AddWithValue("@gEmail", gEmail);
                Object result = cmd5.ExecuteScalar();
                con5.Close();
                if (result != null)
                {
                    lblMessage.Text = "This e-mail is already registered. If you forgot your password, use forgot password link to recover it.";
                    return;
                }
                else
                {
                    string providerName = "Google";
                    string conn = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                    string query = "INSERT INTO Members(Name, Email, ProviderName)values(@gName,@gEmail,@providerName)";
                    using (SqlConnection connection = new SqlConnection(conn))
                    {
                        using (SqlCommand cmd1 = new SqlCommand(query, connection))
                        {
                            cmd1.Parameters.AddWithValue("@gName", gName);
                            cmd1.Parameters.AddWithValue("@gEmail", gEmail);
                            cmd1.Parameters.AddWithValue("@providerName", providerName);
                            connection.Open();
                            cmd1.ExecuteNonQuery();
                            Session.Add("GEmail", gEmail);
                            Session.Add("CurrentUserName", gName);
                            Response.Redirect("ExternalRegistration.aspx");
                            connection.Close();
                        }
                    }
                }
            }
        }
    }

以下是GoogleUserOutputData类和Google登录方法

 public class GoogleUserOutputData
    {
        public string id { get; set; }
        public string name { get; set; }
        public string given_name { get; set; }
        public string email { get; set; }
        public string picture { get; set; }
    }
protected void btnGoogleLogin_Click(object sender, System.EventArgs e)
    {
        var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
        Session["Provider"] = "Google";
        Response.Redirect(Googleurl);
    }

我得到的例外是:&#34;参数化查询&#39;(@ gEmail nvarchar(4000))SELECT Email FROM Members where Email = @ g&#39;期望参数&#39; @ gEmail&#39;,这是未提供的。&#34;

1 个答案:

答案 0 :(得分:1)

您确实需要详细了解如何使用Asynchronous Programming

如果在没有await关键字的情况下调用getgoogleplususerdataSer(),则在方法结束之前,代码块的执行仍会继续。

所以:

private async Task callingMethod()
{
    getgoogleplususerdataSer();
    Console.WriteLine(gName); // maybe null, runs before the end of previous method.
    Console.WriteLine(gEmail); // maybe  null
}

代替:

private async Task callingMethod()
{
    await getgoogleplususerdataSer(); // wait for this to end, then continue.
    Console.WriteLine(gName); // null
    Console.WriteLine(gEmail); // null
}