异步线程使用的阻塞问题async await 举例
程序开发
2023-09-22 09:10:46
问题描述:我们在按钮事件下直接调用异步线程,会出现阻塞,程序卡死现象。如图点击直接运行按钮的效果
解决方法:在线程内运行异步线程,可以解决阻塞问题。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApplication5
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private int PointWork(int i){return i;}private async Task OnePointWorAscnic(int i){int m = await Task.Run(() => PointWork(i));return m;}public void Work(){List> TaskList = new List>();List points = new List { 1, 2, 3 };foreach (var i in points){Task m = OnePointWorAscnic(i);TaskList.Add(m);}foreach (var task in TaskList){int j = task.Result; }MessageBox.Show("运行完成");}private void button1_Click(object sender, EventArgs e){Work();}private void button2_Click(object sender, EventArgs e){Task.Run(() => Work());}}
}
标签:
上一篇:
学习笔记-在intellij IDE中使用Ant
下一篇:
相关文章
-
无相关信息