Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous method with foreach

I have some async method

 public static Task<JObject> GetUser(NameValueCollection parameters)
        {
            return CallMethodApi("users.get", parameters, CallType.HTTPS);
        }

And I write method below

public static IEnumerable<JObject> GetUsers(IEnumerable<string> usersUids, Field fields)
{
    foreach(string uid in usersUids)
    {
        var parameters = new NameValueCollection
                             {
                                 {"uids", uid},
                                 {"fields", FieldsUtils.ConvertFieldsToString(fields)}
                             };
        yield return GetUser(parameters).Result;
    }
}

This method is asynchronous? How to write this using Parallel.ForEach?

like image 323
BILL Avatar asked Sep 03 '25 14:09

BILL


1 Answers

Something kind of like this.

public static IEnumerable<JObject> GetUsers(IEnumerable<string> usersUids, Field fields)
{
    var results = new List<JObject>
    Parallel.ForEach(usersUids, uid => {
        var parameters = new NameValueCollection
                             {
                                 {"uids", uid},
                                 {"fields", FieldsUtils.ConvertFieldsToString(fields)}
                             };
        var user = GetUser(parameters).Result;
        lock(results)
            results.Add(user);
    });
    return results;
}

NOTE: The results won't be in the same order as you expect.

like image 159
Orion Edwards Avatar answered Sep 05 '25 03:09

Orion Edwards