WPF 按钮事件,非UI堵塞
实例:按钮异步事件,非UI堵塞
// 按钮事件,异步事件,获取结果,非UI堵塞 private async void WindowTask_Click(object sender, EventArgs e) { string getstr = await Task.Run<string>(() => { return HttpPost(""); }); } public string HttpPost(string Url, string postDataStr = "") { Thread.Sleep(100000); return ""; }
或者
/// <summary> /// 按钮事件,异步事件,获取结果,非UI堵塞 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void WindowTask_Click(object sender, EventArgs e) { string getstr = await GetHttpPostStringAsync(this.textBox1.Text); } /// <summary> /// 异步请求,返回请求结果 /// </summary> /// <param name="Url">请求地址</param> /// <returns>参数列表</returns> public async Task<string> GetHttpPostStringAsync(string Url) { return await Task.Run<string>(() => { return HttpPost(Url); }); } /// <summary> /// HTTP POST请求 /// </summary> /// <param name="Url">URL地址</param> /// <param name="postDataStr">参数字符串</param> /// <returns>返回结果</returns> public string HttpPost(string Url, string postDataStr = "") { string responseData = ""; return responseData; }
MVVM模式
<Button Content="非阻塞" Width="100" Height="50"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:InvokeCommandAction Command="{Binding CommandClcikAsync}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button>
private DelegateCommand commandClcikAsync; public DelegateCommand CommandClcikAsync => commandClcikAsync ?? (commandClcikAsync = new DelegateCommand(async () => await ClcikAsync())); private async Task ClcikAsync() { await Task.Run<string>(() => { return HttpPost("Url"); }); } public string HttpPost(string Url) { Thread.Sleep(100000); return ""; }
阻塞模式
阻塞1
System.Windows.Application.Current.Dispatcher.Invoke(() => { 阻塞时间 });
阻塞2
System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate() { Thread.Sleep(100000); });
阻塞3
private DelegateCommand commandClcik; public DelegateCommand CommandClcik => commandClcik ?? (commandClcik = new DelegateCommand(() => { Thread.Sleep(100000); }));