k
using System.Text.Json; namespace WinFormsApp { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } /// <summary> /// 更新消息框 /// </summary> /// <param name="msg"></param> public void UpdateMsg(string msg) { if (txtMsg.InvokeRequired) { Action<string> action = UpdateMsg; Invoke(action, msg); return; } txtMsg.AppendText(msg + "\r\n"); //滚动到底部 txtMsg.ScrollToCaret(); } /// <summary> /// 启用、禁用 按钮。 /// </summary> /// <param name="enabled"></param> private void SetBtnEnable(bool enabled) { if (btnStart.InvokeRequired) { Action<bool> action = SetBtnEnable; Invoke(action, enabled); return; } btnStart.Enabled = enabled; } /// <summary> /// 开始执行线程 /// </summary> private async void btnStart_Click(object sender, EventArgs e) { //开启一个子线程,不然等待时会卡主线程。 await Task.Run(async () => { await TestIt(); }); } public async Task TestIt() { //搞个集合 List<int> list = new List<int>(); for (int i = 0; i < 10; i++) { list.Add(i); } //任务集合 List<Task> tasks = new List<Task>(); //执行方法体 Func<int, string> func = (id) => { using (var context = new XCGDbContext()) { var stus = context.Students.Where(x => x.Id == id).FirstOrDefault(); if (stus == null) { return "id:" + id + " 无数据"; } var str = JsonSerializer.Serialize(stus); return str; } }; int maxTaskCount = 3; foreach (int i in list) { int k = i; tasks.Add(Task.Run(() => { var res = func(k); UpdateMsg(res); })); //判断线程数量不能超过最大设定数。 if (tasks.Count > maxTaskCount) { //等待任何一个完成,会卡当前线程。 Task.WaitAny(tasks.ToArray()); //排除掉已完成的任务 tasks = tasks.Where(t => t.Status != TaskStatus.RanToCompletion).ToList(); } } TaskFactory taskFac = new TaskFactory(); //不卡主线程,所有Task完成,才执行下面的操作 await taskFac.ContinueWhenAll(tasks.ToArray(), arr => { //全部完成,执行其他操作... UpdateMsg("执行完毕"); }); } } }