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

api用的框架Flurl;

        public async Task<ApiRespone<QueryDocLoginModel>> 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<ApiRespone<QueryDocLoginModel>>();
                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<QueryDocLoginModel> 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("登录失败");
            }
        }

猜你喜欢

转载自www.cnblogs.com/wangyinlon/p/12012469.html