【问题标题】:Async Await inside a loop for several RESTful calls循环内的异步等待几个 RESTful 调用
【发布时间】:2018-09-21 04:22:49
【问题描述】:

我有一个托管在 azure 上的网络作业,它需要在一个循环中进行多个异步调用。我需要您对最佳性能所需要遵循的方法的专家意见。 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

}

【问题讨论】:

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


    【解决方案1】:
    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 =>
    {
       .....
    });
    

    【讨论】:

    • 我需要等待 var profile = await getUserProfile(userid);
    • 如果 getUserProfile 正在异步执行,那么是的。假设 getUserProfile 需要 20 秒,如果你把 await 你的线程可以切换到处理队列中的另一个请求..看看这篇文章msdn.microsoft.com/en-us/magazine/dn802603.aspx .
    • 另外,当使用 Parallel.ForEach 时,我不能在 in 中使用 await 运算符。Await 只能在异步 lambda 表达式中使用
    • 尝试将异步放在(用户)之前 =>
    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2021-04-15
    • 2019-02-15
    • 2019-02-18
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多