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

本文关键字:分配 全局变量 异步方法 使用 | 更新日期: 2023-09-27 17:57:07

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

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);
    }

我得到的异常是:"参数化查询'(@gEmail nvarchar(4000))选择电子邮件来自电子邮件=@g的成员'需要参数'@gEmail',但未提供。

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

你真的需要阅读更多关于如何使用异步编程的信息。

如果在没有 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
}