简体   繁体   English

Async/Await with Tasks.WhenAll in For 循环未并行运行

[英]Async/Await with Tasks.WhenAll in For Loop Not Running In Parallel

tI'm doing a data migration where I have a long list of pets that I am looping through to perform the migration.我正在执行数据迁移,其中有一长串宠物,我正在循环执行迁移。 In order to migrate each pet a lot of business logic has to be done.为了迁移每个宠物,必须完成大量业务逻辑。 I'd like to have multiple migration tasks running at once to speed this along, but the async addition to the below seems to be operating that same as it would synchronously.我希望一次运行多个迁移任务以加快速度,但是下面的异步添加似乎与同步运行相同。 I've found several stack overflow responses and blog posts about this, but for some reason this still isn't working.我发现了几个关于此的堆栈溢出响应和博客文章,但由于某种原因,这仍然无法正常工作。

I tried to keep the code below to the minimum required, but if more context is needed I can provide that.我试图将下面的代码保持在最低要求,但如果需要更多上下文,我可以提供。

public static async Task MigrationAsync(MyDbContext myContext)
{
    await MainMigrationAsync(myContext);

}

public static async Task MainMigrationAsync(MyDbContext myContext)
{
    var pets = myContext.Pets.ToList();

    var tasks = new List<Task>();
    for (var eachPet = 0; eachRelation < pets.Count; eachRelation++)
    {
        var task = SingleLongRunningPetMigrationAsync(myContext, pets[eachPet]);
        tasks.Add(task);
    }
    await Task.WhenAll();

    myContext.SaveChanges();
}

public static async Task SingleLongRunningPetMigrationAsync(MyDbContext myContext, Pet pet)
{
    //these need to run synchronously for each pet, but need multiple pet tasks to be running at once
    MigrationMethodOne(myContext);
    MigrationMethodTwo(myContext);
    MigrationMethodThree(myContext);
    MigrationMethodFour(myContext);
}

Important: Since EF core doesn't allow parallel usage of a DbContext you must provide one DbContext per "job".重要提示:由于 EF 核心不允许并行使用DbContext ,您必须为每个“作业”提供一个DbContext

And there is no await in the SingleLongRunningPetMigrationAsync method, so it should not be of type async Task , just void .而且SingleLongRunningPetMigrationAsync方法中没有await ,所以它不应该是async Task类型,只是void

You could for instance use a " Parallel.ForEach " in your scenario (given that each call gets its own DbContext ).例如,您可以在场景中使用“ Parallel.ForEach ”(假设每个调用都有自己的DbContext )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM