C#多线程、异步

1.如果数据仅用于展示,或者对数据的获取没有先后要求,可以使用如下线程

 
 private void AutoUpdate_Loaded(object sender, RoutedEventArgs e)
{Thread ThreadUpdate = new Thread(Update);}

private void Update()
{
try
{
Thread.Sleep(2000);

//执行更新
ExcuteUpdate();

Dispatcher.BeginInvoke(new Action(delegate
{
this.Close(); //执行界面层:关闭窗体
}));

}
catch (Exception ex)
{
  MessageBox.Show(ex.Message);
}
}

2.异步

 /// <summary>
        /// 登录验证
        /// </summary>
        /// <returns></returns>
        public async Task<bool> LoginVerfication()
        {
            bool ret = true;
            if (EditCustomSetting == null || EditCustomSetting.LoginUserCode.IsNullOrEmpty() || EditCustomSetting.Password.IsNullOrEmpty())
            {
                await App.Current.MainPage.DisplayAlert("提示", "登录名和密码不能为空,请检查!", "确定");
                return false;
            }
            //获取用户配置
            var result = await service.WebApiLogin(EditCustomSetting.LoginUserCode, EditCustomSetting.Password, EditCustomSetting.ClientCode);
            if (!result.IsSucess)
            {
                await Task.Delay(1000);
                var data = await service.WebApiLogin(EditCustomSetting.LoginUserCode, EditCustomSetting.Password, EditCustomSetting.ClientCode);
                if (!data.IsSucess)
                {
                    await App.Current.MainPage.DisplayAlert("提示", data.Message, "确定");
                    return false;
                }
            }
            return ret;
        }

  

posted @ 2023-04-20 10:03  马玲  阅读(17)  评论(0编辑  收藏  举报