简体   繁体   English

在循环内异步等待几个RESTful调用

[英]Async Await inside a loop for several RESTful calls

I have a webjob hosted over azure which needs to make several async calls in a loop. 我在azure上托管了一个webjob,它需要在循环中进行几个异步调用。 I need your expert inputs on the approach that needs to be followed for optimal performance. 我需要您的专家意见,以寻求最佳性能时必须遵循的方法。 getpermissions1 and getpermissions2 make several restful calls internally (Max 300) getpermissions1和getpermissions2在内部进行了多个静态呼叫(最多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);
});

another way: 其他方式:

users.ToList().AsParallel().ForAll(async user =>
{
   .....
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM