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?
Something kind of like this.
NOTE: The results won't be in the same order as you expect.
Your method is not asynchronous. Assuming your
GetUser
method already starts an asynchronous task,Parallel.ForEach
would use additional threads just to start off your tasks, which is probably not what you want.Instead, what you probably want to do is to start all of the tasks and wait for them to finish:
If you also want to start them in parallel you can use PLINQ:
Both code snippets preserve relative ordering of uids and returned objects -
result[0]
corresponds tousersUids[0]
, etc.