I had a foreach loop which used to loop Membership users and create list of a custom class. Following was the for loop:
foreach (MembershipUser usr in userlist) { userandGroup usrgp = new userandGroup(); usrgp.id = ((Guid)usr.ProviderUserKey).ToString() ; usrgp.Name = usr.UserName; ProfileBase profile = ProfileBase.Create(usr.UserName); profile.Initialize(usr.UserName, true); // Following line takes approx 40ms to execute once. usrgp.DisplayName = profile.GetPropertyValue("FirstName").ToString() + " " + profile.GetPropertyValue("LastName").ToString(); usrgp.type = "user"; lst.Add(usrgp); }
As the commented line used to take approx 40ms to execute, the whole loop for 40 users used to take approx 1600ms to execute.
I got suggestion to use Parallel.ForEach loop to reduce the execution time of the loop from this question
SO I updated the loop as:
Object obj = new Object();
Parallel.ForEach(userlist, (usr) =>
{
userandGroup usrgp = new userandGroup();
usrgp.id = ((Guid)usr.ProviderUserKey).ToString();
usrgp.Name = usr.UserName;
ProfileBase profile = ProfileBase.Create(usr.UserName);
profile.Initialize(usr.UserName, true);
usrgp.type = "user";
usrgp.DisplayName = profile.GetPropertyValue("FirstName").ToString() + " " + profile.GetPropertyValue("LastName").ToString();
lock (obj)
{
lst.Add(usrgp);
}
});
The loop works. Now the performance is way better (Although not best). It now takes only 700ms to execute the loop.
But I am not sure if it is the correct way to write Parallel.ForEach loop as I am new to it. Kindly suggest if the code is right?
Parallel.ForEach
loop because e.g. thelst
is not defined here so we don't know what it is. \$\endgroup\$