c# - Windows 窗体卡在多个异步任务上

标签 c# .net winforms async-await task

我正在尝试执行并行方法,但是每当 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/

相关文章:

c# - Xamarin - 设置跨平台 Hello World App

c# - 使用 LINQ 编写 'CONTAINS' 查询

c# - 当我真的需要继承两个类时如何处理CS1721?

c# - 如何在 C# 中刷新表单?

c# - 从 VBScript 调用 .NET COM 对象

c# - 如何在执行其他具有许多重载的方法之前/之后每次执行一个方法?

c# - Firefox 上的 Javascript 函数问题未通过 jquery 键盘输入启动计数器(适用于 Chrome 和 IE)

c# - 如何通过以下语法访问 C# 字典元素?

c# - 在winforms中多次运行 "FFMPEG"

c# - 使用 c# 将 typeof(DateTime) 更改为仅日期