我有以下代码,其中我使用MembershipUser
数组创建自定义类的列表。
以下是创建其列表的自定义类:
public class userandGroup :IComparable{
public string id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public string type { get; set; }
public int? CompareTo(Object obj)
{
if (obj is userandGroup)
return this.DisplayName.CompareTo((obj as userandGroup).DisplayName);
return null;
}
}
以下是填充userlist
的代码:
MembershipUserCollection tempuserlist = GetProvider("DefaultProfileProvider", applicationName).GetAllUsers(currentPage - 1, pageSize, out totalUsers);
MembershipUser[] userlist = new MembershipUser[totalUsers];
tempuserlist.CopyTo(userlist, 0);
以下是生成userandGroup
(自定义类)列表的代码:
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 approximately takes 40ms per loop.
usrgp.DisplayName = profile.GetPropertyValue("FirstName").ToString() + " " + profile.GetPropertyValue("LastName").ToString();
usrgp.type = "user";
lst.Add(usrgp);
}
如评论中所写,行;
usrgp.DisplayName = profile.GetPropertyValue("FirstName").ToString() + " " + profile.GetPropertyValue("LastName").ToString();
在一个循环中完成需要40ms。我现在有40个用户。因此,循环需要大约1600ms才能执行。如果用户数量增加,循环将花费可怕的时间来完成。
如何减少线路的执行时间,还是有其他方法可以从ProfileBase
获取用户的名字和姓氏?
答案 0 :(得分:0)
根据@TyCobb的建议,我使用了Parallel Foreach循环。我按如下方式更新了循环。
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);
}
});
虽然性能稍有改善,但性能尚不理想。现在整个循环在不到一秒的时间内完成。