【发布时间】:2022-08-16 02:36:23
【问题描述】:
我正在进行代码性能优化,需要建议使用parallel.foreach 和/或WhenAll 实现async 的最佳方法。
代码分为三个主要区域。
Code Definition
MethodA 提取Customer 列表
MethodBPartA 循环遍历客户并通过Azure Function 从数据库中选择记录。这是 1:* 关系,因此 1 个客户可以有多个记录。
MethodB PartB 查看在方法 B 部分 A 中选择的客户记录列表,看看是否有任何附加文件。如果有文件/文件,则处理并将“客户参考”发送回“方法A”,将记录存储在字典中。然后它发送
方法A
public async Task<List<Customers>> MethodA(){
List<Customer> customers = await GetAllCustomers();
var inboundCustomerFiles= new List<InboundCustomerFiles>();
Parallel.ForEach(customer, async customer =>
{
var processedCustomer = await MethodB(customer);
inboundCustomersFiles.AddRange(processedCustomer);
});
}
方法B
public static async Task<List<InboundCustomerFiles>> MethodB(Customer customer){
var customerRecord = await GetCustomerRecord(customerId);
foreach(var customer in customerRecord){
var files = await getCustomerRecordFile(customerRecordId)
//...... remaining code
}
return inboundCustomerFiles;
}
方法三
public static async Task<List<InboundCustomerFiles>> GetCustomerRecord(int customerId){
//API call here that further pull `record` from database
return List<Records>();
}
methodB customerRecord 中的过程需要时间。我如何确保它处理数据并返回到 MethodA 中的正确客户线程。我曾尝试在 methodB 中使用,但它变慢了,进一步我知道 Parallel.Foreach 不会等待,所以我尝试在 lambda 表达式中添加 async 引用,但不确定 A 是否正确或是否有效。
-
Parallel.ForEachis not async-friendly。 -
你能在上面的客户场景中帮助我吗,我需要一些指导……非常感谢
-
我想运行
Customer多个实例,我应该使用什么来代替Parallel>forEach? -
您已经解释了客户和记录之间的关系(一对多),但是您还没有解释这两个实体和“文件”实体之间的关系。文件是与客户相关还是与记录相关?以及它们之间的关系是什么?
-
该文件与
record相关并且是1:*关系,因此1 条记录可以有0 个或多个文件
标签: c# async-await parallel.foreach