加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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 Cleary的博客,这里有http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-even-in.html所以请花一些时间来完成这个,看看哪个适合你的项目.

或者在这里查看Stephen https://stackoverflow.com/a/18015586的其他细节

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读