winform/wpf调用异步api正确姿势,界面不卡

api用的框架Flurl;

        public async Task> QueryDocLogin(string ysdm, string pwd)
        {
            try
            {
                Thread.Sleep(5000);
                var responseString = await (ConfigurationManager.AppSettings["ApiHost"] + "/HisApi/Triage/QueryDocLogin")
                    .SetQueryParams(new { ysdm = ysdm, pwd = pwd })
                  .GetJsonAsync>();
                return responseString;
            }
            catch (Exception e)
            {
                YinLong.Framework.Logs.Log4.Debug("[QueryDocLogin异常]:" + e.ToString());
                return null;
            }
        }

按钮事件

        private async void ButtonLogin_OnClick(object sender, RoutedEventArgs e)
        {
            Apis apis = new Apis();
            string account = TextBoxAccount.Text;
            string pass = Password.Password;
            ButtonLogin.Content = "登录中";
            ButtonLogin.IsEnabled = false;
            ApiRespone model = null;
            await Task.Run(delegate
             {
                 model = apis.QueryDocLogin(account, pass).Result;

             });

            if (model != null)
            {
                Configs.QueryDocLoginModel = model;
                this.Dispatcher.Invoke(new Action(delegate
                {
                    new MainWindow().Show(); // 显示主窗口;
                    Close();
                }));
            }
            else
            {
                this.Dispatcher.Invoke(new Action(delegate
                {
                    ButtonLogin.Content = "登录";
                    ButtonLogin.IsEnabled = true;
                }));
                MessageBox.Show("登录失败");
            }
        }

 

你可能感兴趣的:(winform/wpf调用异步api正确姿势,界面不卡)