如何使用Await方法加载新页面 [英] How to load new page with Await method

查看:95
本文介绍了如何使用Await方法加载新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的登录方法:

    #region LoginMethod
    bool login = false;
    public async Task GetAccounts()
    {
        MainWin w = new MainWin();

        await Task.Run(() =>
        {
            this.Dispatcher.Invoke(() =>
            {
                using (SqlConnection connection = new SqlConnection(PublicVar.ConnectionString))
                {
                    gymEntities2 database = new gymEntities2();
                    SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);
                    PublicVar.TodayTime = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(TimeNow.Text));
                    con1.Open();

                    SqlCommand Actives = new SqlCommand("Select DISTINCT (LockEndDate) from LockTable Where Username = '" + txt_username.Text + "' and Password = '" + txt_password.Password + "'", con1);
                    object Active = Actives.ExecuteScalar();
                    string SystemActive = Convert.ToString(Active);

                    //   SqlCommand Commandcmds = new SqlCommand("update VW_TimeOut set UserActive = 2 where UserEndDate < '" + String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(TimeNow.Text)) + "'", con1);
                    //   Commandcmds.ExecuteScalar();

                    SqlCommand Commandcmd = new SqlCommand("SELECT COUNT(*) FROM LockTable Where Username = '" + txt_username.Text + "' and Password = '" + txt_password.Password + "' and LockEndDate between '" + String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(Lock.Text)) + "' And '" + SystemActive + "'", con1);
                    int userCount = (int)Commandcmd.ExecuteScalar();

                    //Find Gym ID -> To Set Public Value Strings
                    SqlCommand FindGymID = new SqlCommand("Select DISTINCT (LockID) from LockTable Where Username = '" + txt_username.Text + "' and Password = '" + txt_password.Password + "'", con1);
                    object ObGymID = FindGymID.ExecuteScalar();

                    if (userCount > 0)
                    {
                        try
                        {
                            RegistryKey UsernameKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\GYM");

                            if (CheakRem.IsChecked == true)
                                if ((string)UsernameKey.GetValue("UserNameRegister") != "")
                                {
                                    UsernameKey.SetValue("UserNameRegister", txt_username.Text.Trim());
                                    UsernameKey.SetValue("PasswordRegister", Module.Decode.EncryptTextUsingUTF8(txt_password.Password.Trim()));
                                }

                            PublicVar.GymID = Convert.ToString(ObGymID);
                            login = true;
                        }
                        catch
                        {

                            w.Username = null;
                            w.Password = null;
                        }
                    }
                    else
                    {
                        ErrorPage pageerror = new ErrorPage();

                        con1.Close();
                        w.Username = null;
                        w.Password = null;
                    }
                    con1.Close();
                }
            });
        });

        if (login == true)
        {
            w.Username = txt_username.Text;
            w.Password = txt_password.Password;
            w.Show();
            this.Close();
        }
    }
    #endregion

但是它不起作用-每当我按下按钮时,我的表单就会挂起.

But it doesn't work - my form is going to hang whenever I press the button.

private async void btn_join_Click(object sender, RoutedEventArgs e)
{
    await GetAccounts();
}

它不起作用,并且当我按下异步按钮时我的程序被挂起. 我的方法的哪一部分是错误的? 我真正想要的是按下按钮以打开新页面, 但我不希望它延迟打开……有人告诉我使用await方法,但它仍然会延迟打开.

It doesn't work and my program is getting hung when I press the async button. What part of my method is wrong? What i actually want is the button press opening a new page, but I don't want it to open with delay... I was told to use an await method, but it still opens with delay.

推荐答案

以上两个答案都是正确的.但是也许修复您的代码将使事情变得更清楚.您应该按照上面的建议并如下所示将UI与任务"分开.希望我没有语法错误,因为我只是在没有IDE的情况下对其进行了修改.基本上,我将GetAccounts更改为仅处理数据库,而让PopulateMethodAsync处理UI.这意味着GetAccounts将在后台运行,完成后会将结果提供给UI部分(PopulateMethodAsync).

Both answers above are correct. But maybe fixing your code will make things more clear. You should separate the UI from Tasks as suggested above and as shown below. Hopefully, I don't have syntax errors since I just modified it without IDE. Basically, I changed GetAccounts to only deal with the database and let PopulateMethodAsync to deal with the UI. This means GetAccounts will be working in the background and when it is done, it will give the result to the UI section (PopulateMethodAsync).

    #region LoginMethod
    bool login = false;
    public async Task PopulateMethodAsync()
    {
        var isLoginSuccess = await GetAccounts(txt_username.Text.Trim(), txt_password.password.Text.Trim(), Lock.Text.Trim(), TimeNow.Text.Trim());

        MainWin w = new MainWin();

        if (login == true)
        {
            w.Username = txt_username.Text;
            w.Password = txt_password.Password;
            w.Show();
            this.Close();
        }
        else
        {
            w.Username = null;
            w.Password = null;
        }
    }

    public async Task<bool> GetAccounts(string txt_username, string txt_password, string Lock, string TimeNow)
    {
        await Task.Run(() =>
        {
            using (SqlConnection connection = new SqlConnection(PublicVar.ConnectionString))
            {
                gymEntities2 database = new gymEntities2();
                SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);
                PublicVar.TodayTime = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(TimeNow));
                con1.Open();

                SqlCommand Actives = new SqlCommand("Select DISTINCT (LockEndDate) from LockTable Where Username = '" + txt_username + "' and Password = '" + txt_password + "'", con1);
                object Active = Actives.ExecuteScalar();
                string SystemActive = Convert.ToString(Active);

                //   SqlCommand Commandcmds = new SqlCommand("update VW_TimeOut set UserActive = 2 where UserEndDate < '" + String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(TimeNow.Text)) + "'", con1);
                //   Commandcmds.ExecuteScalar();

                SqlCommand Commandcmd = new SqlCommand("SELECT COUNT(*) FROM LockTable Where Username = '" + txt_username + "' and Password = '" + txt_password + "' and LockEndDate between '" + String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(Lock)) + "' And '" + SystemActive + "'", con1);
                int userCount = (int)Commandcmd.ExecuteScalar();

                //Find Gym ID -> To Set Public Value Strings
                SqlCommand FindGymID = new SqlCommand("Select DISTINCT (LockID) from LockTable Where Username = '" + txt_username + "' and Password = '" + txt_password + "'", con1);
                object ObGymID = FindGymID.ExecuteScalar();

                if (userCount > 0)
                {
                    try
                    {
                        RegistryKey UsernameKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\GYM");

                        if (CheakRem.IsChecked == true)
                            if ((string)UsernameKey.GetValue("UserNameRegister") != "")
                            {
                                UsernameKey.SetValue("UserNameRegister", txt_username);
                                UsernameKey.SetValue("PasswordRegister", Module.Decode.EncryptTextUsingUTF8(txt_password));
                            }

                        PublicVar.GymID = Convert.ToString(ObGymID);

                        con1.Close();

                        return true;
                    }
                    catch
                    {

                    }
                }

                con1.Close();
            }
        });

        return false;
    }
    #endregion

    private async void btn_join_Click(object sender, RoutedEventArgs e)
    {
        await PopulateMethodAsync();
    }

希望这能回答您的问题

这篇关于如何使用Await方法加载新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆