并行http发布请求(多线程)C#

时间:2017-11-19 12:42:44

标签: c# multithreading http concurrency parallel-processing

我如何制作,例如c#中的10个并行http post请求(同时发送它们)?我正在使用xNet库来处理请求和响应。这是代码:

private void getUsersFromGroup(string groupId)
        {
            HttpRequest request = new HttpRequest();
            RequestParams rp = new RequestParams();
            HttpResponse res;
            string resStr;

            rp["offset"] = "0";
            rp["count"] = "1000";
            rp["online"] = "1";                
            rp["group_id"] = groupId;                
            rp["access_token"] = access_token;
            rp["v"] = apiVersion;
            res = request.Post(Api + "users.search", rp);
            resStr = res.ToString();

            var obj = JsonConvert.DeserializeObject<RootObject>(resStr);
            if (obj.response.count != 0)
            {
                foreach (var item in obj.response.items)
                {
                        if (!usersID.Contains(item.id))
                        {
                            usersID.Add(item.id);
                        }

                }

            }

        }

我在foreach循环中调用这个方法顺便说一下,也许它会改变一些东西。

public void getUsers()
        {
            foreach (string groupID in groups)
            {
                getUsersFromGroup(groupID);
            }
        }

我希望每秒能发送3个API请求。我该怎么办?

2 个答案:

答案 0 :(得分:0)

如果您不想使用ThreadPool,您可以在分离的线程上运行您的方法,如下所示:

foreach (var groupId in groupIds) {
    var thread = new System.Threading.Thread(() => getUsersFromGroup(groupId));
    thread.Start();
}

答案 1 :(得分:0)

你一定要尝试Task.WhenAll。示例代码如下所示:

public async Task<IEnumerable<UserDto>> GetUsersInParallel(IEnumerable<int> userIds)
{
    var tasks = userIds.Select(id => client.GetUser(id));
    var users = await Task.WhenAll(tasks);

    return users;
} 

public async Task<UserDto> GetUser(int id)
{
    var response = await client.GetAsync("http://youraddress/api/users/" + id)
        .ConfigureAwait(false);
    var user = JsonConvert.DeserializeObject<UserDto>(await response.Content.ReadAsStringAsync());

    return user;
}

有关完整分析和更多代码,请访问我的博文:http://www.michalbialecki.com/2018/04/19/how-to-send-many-requests-in-parallel-in-asp-net-core/