0
从新线程中声明的局部变量的用法有任何区别吗?线程中的外部变量用法
string emailSubject = "New message notification";
string imagePath = somePath;
string conversationName = entity.Name;
new Thread(delegate()
{
foreach (var user in participantList)
{
string newEmailBody = emailBody.Replace("###ImagePath###", imagePath)
.Replace("###UserName###", user.Name)
.Replace("###ConversationName###", conversationName);
MailUtil.SendEmail(user.Email, emailSubject, newEmailBody);
}
}).Start();
在新线程中声明它们更安全吗?就像这样:
new Thread(delegate()
{
string emailSubject = "New message notification";
string imagePath = somePath;
string conversationName = entity.Name;
foreach (var user in participantList)
{
string newEmailBody = emailBody.Replace("###ImagePath###", imagePath)
.Replace("###UserName###", user.Name)
.Replace("###ConversationName###", conversationName);
MailUtil.SendEmail(user.Email, emailSubject, newEmailBody);
}
}).Start();
垃圾回收器呢?对于第一个变体,GC会“知道”这些变量仍在使用中吗? – Pal
@Pal是的。 GC足够聪明,可以跟踪这些变量。在第一种情况下,应用所谓的“封闭”程序。一般来说,你不应该对GC感到担心,但了解GC的算法可以帮助你更好地设计你的应用程序。 –