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

时间:2018-09-21 04:22:50

标签: c# multithreading rest async-await task-parallel-library

我有一个托管在天蓝色的webjob,需要在循环中进行几个异步调用。我需要您的专家意见,以寻求最佳性能时必须遵循的方法。 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

}

1 个答案:

答案 0 :(得分:0)

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 =>
{
   .....
});