从循环中调用 C# 异步方法并确保结果返回到同一线程。线程安全
我正在致力于代码性能优化。我在 MethodA
中实现了 Task.WhenAll
,它调用 MethodB
,它选择 awaitcustomersRecords
。到这里为止都还好。在步骤中,我正在查看 customerRecord 并调用另一个方法 await Task getCustomerRecordFilesLocation
来通过 customerRecord
选择文件夹位置,但出现错误,表明已定义具有相同键的项目。这发生在多个记录上。
如果我将 MethodA
替换为经典循环,并将 getCustomerRecordFilesLocation
替换为异步调用,那么我不会收到错误。
我相信理想情况下我想确保 getCustomerRecordFilesLocation 等待并且结果返回到正确的线程?我已经在 foreach(var customer in customerRecord)
代码上尝试了 lock()
但仍然收到错误:
System.Private.CoreLib:已添加具有相同键的项目。密钥:g65434fr-5b5v-42wc-8a83-123456789054。
方法A
public async Task<List<Customers>> MethodA(){
List<Customer> customers = await GetAllCustomers();
var inboundCustomerFiles= new List<InboundCustomerFiles>();
await Task.WhenAll(customers.Select(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 folderLocation = await Task.Run(() => getCustomerRecordFilesLocation(customerRecordId)); //Need help here... Get error key already been added
}
return inboundCustomerFiles;
}
I am working on code performance optimizing. I have implemented Task.WhenAll
in MethodA
which calls MethodB
which picks await customersRecords
. Up to here is fine. In step I am looking through customerRecord and calling another method await Task getCustomerRecordFilesLocation
to pick folders location by customerRecord
but getting error that items with same key already defined. This is happening on multiple records.
If I replace MethodA
with classic loop and getCustomerRecordFilesLocation
with async call then I don't get error.
I believe ideally I want to ensure getCustomerRecordFilesLocation
wait and it result goes back in correct thread?? I have tried lock()
on foreach(var customer in customerRecord)
code but still getting error:
System.Private.CoreLib: An item with the same key has already been added. Key: g65434fr-5b5v-42wc-8a83-123456789054.
MethodA
public async Task<List<Customers>> MethodA(){
List<Customer> customers = await GetAllCustomers();
var inboundCustomerFiles= new List<InboundCustomerFiles>();
await Task.WhenAll(customers.Select(async customer =>
{
var processedCustomer = await MethodB(customer);
inboundCustomersFiles.AddRange(processedCustomer);
});
}
MethodB
public static async Task<List<InboundCustomerFiles>> MethodB(Customer customer){
var customerRecord = await GetCustomerRecord(customerId);
foreach(var customer in customerRecord){
var folderLocation = await Task.Run(() => getCustomerRecordFilesLocation(customerRecordId)); //Need help here... Get error key already been added
}
return inboundCustomerFiles;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论