简体   繁体   中英

Parallel http post requests (Multithreading) C#

How can I make, for example 10 parallel http post requests in c# (send them at the same time)? I'm using xNet library to work with requests and response. Here's code:

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);
                        }

                }

            }

        }

Im calling this method in foreach loop btw, maybe it would change something.

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

I want to be able to send 3 API request every second. How can I do it?

If you don't want to use ThreadPool you may run you method on separated threads like this:

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

You should definitely try Task.WhenAll. Sample code can look like this:

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;
}

For full analysis and more code go to my blog post: http://www.michalbialecki.com/2018/04/19/how-to-send-many-requests-in-parallel-in-asp-net-core/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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