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

cnblogs.com/fps2tao/p/14683435.html

一、异步更新UI线程--利用委托
C#异步调用,界面假死加更新界面 (此例子更新界面的方法是利用组件的委托方法Control.Invoke())
lblStatus.Text = "执行中,请稍候……";
  
Func<int> longTask = new Func<int>(delegate()
{
    //  模拟长时间任务
    Thread.Sleep(2000);
  
    //  返回任务结果:5
    return 5;
});
//  发起一次异步调用,实际上就是在.net线程池中执行longTask
//  这时由于是其它线程在工作,UI线程未被阻塞,所以窗体不会假死
longTask.BeginInvoke(ar =>
{
    //  使用EndInvoke获取到任务结果(5)
    int result = longTask.EndInvoke(ar);
  
    //  使用Control.Invoke方法将5显示到一个label上,如果没有Invoke,
    //  直接写lblStatus.Text="5",将会抛出跨线程访问UI控件的异常
    Invoke(new Action(() => lblStatus.Text = "执行结果是:" + result));
}, null);

 

再举一个例子:
        private delegate void InvokeCallBackDelegate();
        private void btn_click01_Click(object sender, EventArgs e)
        {
            txt_html.Text = "";
            this.btn_click01.Enabled = false;
            //使用的httpLib库:jthorne.co.uk/httplib.
            Http.Get("http://www.baidu.com").OnSuccess(result =>
            {
                 //下面是返回给界面信息提示
                    this.Invoke(new InvokeCallBackDelegate(delegate ()
                    {
                        txt_html.Text = result;
                        this.btn_click01.Enabled = true;
                    }));

            }).Go();
        }

 

二、异步更新UI线程--利用同步模型中转播上下文
         
        private void btn_http_Click(object sender, EventArgs e)
        {
            SynchronizationContext _uiContext1 = SynchronizationContext.Current;//上下文内容(变量可以作为属性,在窗口实例化时赋值)
            txt_html.Text = "";
            this.btn_http.Enabled = false;
            //使用的httpLib库:jthorne.co.uk/httplib.
            Http.Get("http://www.baidu.com").OnSuccess(result =>
            {
                //若你在业务处理方法内需要对界面控件进行操作就需要这样更新
                _uiContext1.Post(_ =>
                { 
                    txt_html.Text = result;
                    btn_http.Enabled = true;
                }, null);
            }).Go();
        }

 
转 ; 

https://blog.csdn.net/guo449211721/article/details/81262057

https://zhidao.baidu.com/question/314987513.html

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("登录失败");
            }
        }
复制代码
 

作者:银龙
出处:http://www.cnblogs.com/wangyinlon/
-------------------------------------------

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值