Async Await 在一个循环内进行多次 RESTful 调用
Async Await inside a loop for several RESTful calls
我有一个托管在 azure 上的网络作业,它需要在一个循环中进行多个异步调用。我需要您就实现最佳性能所需遵循的方法提供专家意见。 getpermissions1 和 getpermissions2 在内部进行多次 restful 调用(最多 300 次)
//users count is around 40K
foreach (var user in users.ToList())
{
//Get user Profile
var profile = await getUserProfile(userid); // 1 Restful Call
//user profile get 2 sets of permissions
var permissions1 = await getPermission1(profile); //Max 300 Restful Call
//user profile get 2 sets of permissions
var permissions2 = await getPermission2(profile); //Max 300 Restfull Call
//var newProfile = profile + permissions1 + permissions2
//Then post new profile to a Rest API
var response = await client.PostAsync(new Uri(url), newProfile); //Invoke and wait for response to log the message
}
Parallel.ForEach(users.ToList(), async (user) =>
{
//Get user Profile
var profile = await getUserProfile(userid);
//user profile get 2 sets of permissions
var t1 = getPermission1(profile);
//user profile get 2 sets of permissions
var t2 = getPermission2(profile);
await Task.WhenAll(new Task[] { t1, t2 });
//var newProfile = profile + t1.Result + t2.Result
//Then post new profile to a Rest API
var response = await client.PostAsync(new Uri(url), newProfile);
});
另一种方式:
users.ToList().AsParallel().ForAll(async user =>
{
.....
});
我有一个托管在 azure 上的网络作业,它需要在一个循环中进行多个异步调用。我需要您就实现最佳性能所需遵循的方法提供专家意见。 getpermissions1 和 getpermissions2 在内部进行多次 restful 调用(最多 300 次)
//users count is around 40K
foreach (var user in users.ToList())
{
//Get user Profile
var profile = await getUserProfile(userid); // 1 Restful Call
//user profile get 2 sets of permissions
var permissions1 = await getPermission1(profile); //Max 300 Restful Call
//user profile get 2 sets of permissions
var permissions2 = await getPermission2(profile); //Max 300 Restfull Call
//var newProfile = profile + permissions1 + permissions2
//Then post new profile to a Rest API
var response = await client.PostAsync(new Uri(url), newProfile); //Invoke and wait for response to log the message
}
Parallel.ForEach(users.ToList(), async (user) =>
{
//Get user Profile
var profile = await getUserProfile(userid);
//user profile get 2 sets of permissions
var t1 = getPermission1(profile);
//user profile get 2 sets of permissions
var t2 = getPermission2(profile);
await Task.WhenAll(new Task[] { t1, t2 });
//var newProfile = profile + t1.Result + t2.Result
//Then post new profile to a Rest API
var response = await client.PostAsync(new Uri(url), newProfile);
});
另一种方式:
users.ToList().AsParallel().ForAll(async user =>
{
.....
});