c# – Windows窗体卡在多个异步任务上
发布时间:2020-12-15 23:31:02 所属栏目:百科 来源:网络整理
导读:我正在尝试执行并行方法,但Form随时都会被卡住 我打电话给他们. 请纠正我做错了什么.这是代码: public partial class Form1 : Form{ private async void button1_Click(object sender,EventArgs e) { var itemList = new Liststring() { "Field1","Field2",
我正在尝试执行并行方法,但Form随时都会被卡住
我打电话给他们. 请纠正我做错了什么.这是代码: public partial class Form1 : Form { private async void button1_Click(object sender,EventArgs e) { var itemList = new List<string>() { "Field1","Field2","Field3" }; await Task.WhenAll(itemList.Select(item => new WorkToDo(item).StartWork() )); } } public class WorkToDo { private string id; public WorkToDo(string id) { this.id = id; } public async Task<bool> StartWork() { Calculate(); Analyze(); SomeToDo(); var result = Save(); await Task.Delay(100); return result; } private bool Calculate() { //Some complex and time taking calculation will be here return true; } private bool Analyze() { //Some complex and time taking calculation will be here return true; } private bool SomeToDo() { //Some complex and time taking calculation will be here return true; } private bool Save() { //Some complex and time taking calculation will be here return true; } } 解决方法
您需要记住,仍然会在UI线程上执行正常的async / await.
因此,为了确保将一个真正的长动作推送到后台线程,您需要将它包装在Task.Run中…就像Task.Run(()=> Task.WhenAll(tasks)); 为了更多地完成这个问题(看到其他答案可用),Task.Run的使用并不是一件容易的事情.这一切都取决于需要包装的代码类型. 或者在这里查看Stephen https://stackoverflow.com/a/18015586的其他细节 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |