我正在尝试执行并行方法,但是每当 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;
}
}
最佳答案
您需要记住,正常的 async/await 仍将在 UI 线程上执行。
因此,为了确保真正的长 Action 被推送到后台线程,您需要将其包装在 Task.Run 中...就像 Task.Run(() => Task.WhenAll(tasks)) ;
为了进一步完成问题(查看其他可用答案),Task.Run 的使用不是一件容易的事。这完全取决于需要包装什么样的代码。 在 Stephen Cleary 的博客上有一个很好的系列文章 http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-even-in.html因此,请花一些时间来了解一下,看看什么适合您的项目。
或在此处查看 Stephen https://stackoverflow.com/a/18015586 的其他详细信息
关于c# - Windows 窗体卡在多个异步任务上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35292849/