c# - 异步保存到单个 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 的结果,而它们仍然可以像往常一样异步并行保存到数据库中。提前感谢您的见解和帮助:)
解决方案
怎么样:
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;
}
推荐阅读
- sass - SCSS 中的 & 和 mixins
- javascript - PHP If 语句 html 选项值 0
- java - 不能转换为 java.sql.Blob
- nginx - 用于 TCP 上游服务器的 NGINX SSL 终止并在上游传递 TLS 会话详细信息
- liquibase - 如果我们使用 liquibase 在表的中间添加列,如何生成 SQL
- python - 查找字符串中每个不同字符的所有位置的最快方法
- jhipster - 在 jhipster 5.7.2 项目中使用 mybatis ORM 添加第二个数据源的问题
- angular - 如何实现 3 个组件(1 个父组件和 2 个子组件)之间的拖放
- python - Python - 从变量中读取镶木地板数据
- r - 刻度线标签中的数学表达式,ggplot2