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/
-------------------------------------------