var sendlist = emailList.Select(email => new MailMessage {
MailServer = SMTPServer,
UserName = Sender,
PassWord = EmailPassword,
ServerCode = ServerCode,
ToAddr = email.Email,
BCC = string.Empty,
CC = string.Empty,
Title =Tittle,
Body = Content,
BodyText = Description,
}).ToList();
代码如上,emailList是一个List<T>,有五万条记录,结果上面的代码运行居然要用到半小时才完成。经多次调试,的确是时间主要在Lambda表达式上。因为SMTPServer是一个全局变量,并非局总变量,每一行都要重新去获取。
只是一个全局变量就这么慢,那么如果是一个函数呢。
代码变成如下:
var mailServer = SMTPServer
var sendlist = emailList.Select(email => new MailMessage {
MailServer = mailServer,
UserName = Sender,
PassWord = EmailPassword,
ServerCode = ServerCode,
ToAddr = email.Email,
BCC = string.Empty,
CC = string.Empty,
Title =Tittle,
Body = ToContent(Content),
BodyText = Description,
}).ToList();
结过测试,也当出现同样的情况。
为此,在写类似的代码时,不要出现全局变量和函数。
如果非要用到呢?
全局变量的解决方法:把全局变量的值赋给一个局部变量就行了。
如:
var mailServer = SMTPServer
var sendlist = emailList.Select(email => new MailMessage {
MailServer = mailServer,
UserName = Sender,
PassWord = EmailPassword,
ServerCode = ServerCode,
ToAddr = email.Email,
BCC = string.Empty,
CC = string.Empty,
Title =Tittle,
Body = Content,
BodyText = Description,
}).ToList();
函数的方法,暂时没有想到别的方法,只能在修改业务了。