• 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("登录失败");
                }
            }
  • 相关阅读:
    #define用法详解
    memchr函数
    aiohttp模块1 client
    asyncio标准库7 Producer/consumer
    asyncio标准库6 Threads & Subprocess
    asyncio标准库5 TCP echo client and server
    asyncio标准库4 asyncio performance
    asyncio标准库3 HTTP client example
    asyncio标准库2 Hello Clock
    asyncio标准库1 Hello World
  • 原文地址:https://www.cnblogs.com/wangyinlon/p/12012469.html
Copyright © 2020-2023  润新知