首页 > 解决方案 > 异步保存到单个 SQL Server Db 中的多个表

问题描述

我能够使用 Task.WhenAll(tasks) 并行填充数据库的多个表。我对每个表都有一个通用方法:

var tasks = new List<Task>()
        {
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>(),                                                                     
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>()
        };

        await Task.WhenAll(tasks);

现在出现了一个新要求,要求我从该异步方法中保存新项目的数量,我偶然发现了这篇文章。我尝试按照已接受答案的评论中提到的方式进行操作,以获取新项目的数量:

   int newItems = 0;
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>();
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>();
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>();                                                                     
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>();

使用第二种方法,数据库表不会并行更新而是同步更新。

在 CheckNewItem 方法中,我在 EF Core 中使用 SaveChangesAsync 和 AddRangeAsync 方法。我不确定为什么使用 Task.WhenAll(tasks) 会执行所需的操作,而在帖子中某些评论提到您不需要执行 Task.WhenAll 以确保异步时,第二种方式却不会方法并行运行。

我想获得每次调用 CheckNewItems 的结果,而它们仍然可以像往常一样异步并行保存到数据库中。提前感谢您的见解和帮助:)

标签: c#asynchronousasync-awaitentity-framework-core

解决方案


怎么样:

var tasks = new List<Task>()
        {
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>(),                                                                     
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>()
        };

await Task.WhenAll(tasks);
int newItems = 0;
foreach(var task in tasks){
     newItems+= await task;
}

推荐阅读