스레드 Nesting await in Parallel.ForEach에는 Task.WhenAll을 사용하여 다중 (MaxDegreeOfParallelism) 비동기 작업을 병렬로 실행하고 이전 작업이 완료 될 때까지 대기하지 않는 것이 좋습니다.작업 매개 변수 포함 방법 작업 배열 예외 처리
public static Task ForEachAsync<T>(
this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(dop)
select Task.Run(async delegate {
using (partition)
while (partition.MoveNext())
await body(partition.Current).ContinueWith(t =>
{
//observe exceptions
});
}));
}
는 몸이 매개 변수가있는 경우 그리고
ids.ForEachAsync(10, async id =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = await repo.GetCustomer(id);
customers.Add(cust);
});
과 같이 호출, 나는 exceptions.e.g을 처리 할 때 매개 변수 값을 알고 싶어요. id에 대해 작업 본문이 실패한 경우 특정 ID에 대해 예외가 발생했음을 지정하여 예외를 기록해야합니다.
나는 Accessing values in Task.ContinueWith을 보았지만 t.IsFaulted 때 매개 변수에 액세스 할 수 없었습니다. (차단하지 않고, 즉 비동기)
마지막으로 나는 람다 체내 시도/캐치를 추가했습니다 그리고 내가 확실하지 않다 그러나ids.ForEachAsync(10, async id =>
{
try
{
ICustomerRepo repo = new CustomerRepo();
var cust = await repo.GetCustomer(id);
customers.Add(cust);
}
catch(Exception e)
{
_logger.LogError(e,” id=“+ id);
}
});
이 제대로 작동합니까 작동하는 것 같다. 원래 대답 suggested의
나중에 저자는 VAR 전류를 사용하기 = partition.Current 전 (지속에 ContinueWith (t => {...})를 현재 사용 후 몸을 기다리고와 -.
사람이 수 접근 방식이 더있는 확인 상관 없음 단점이 방법의 각각의