2013-08-29 36 views
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(); 

回答

1

由于所有在你的榜样三个贵变量是不可变的(string is immutable)则没有差别,选择哪一个实现。唯一的区别是在第一个例子中你的变量(指针)可以在其他情况下从其他线程改变,这是安全的。但是当你使用复杂类型时,你必须确保你的类型是thread-safe,因为以其他方式对不同线程中的变量进行同时操作可能会导致损坏状态。

+0

垃圾回收器呢?对于第一个变体,GC会“知道”这些变量仍在使用中吗? – Pal

+0

@Pal是的。 GC足够聪明,可以跟踪这些变量。在第一种情况下,应用所谓的“封闭”程序。一般来说,你不应该对GC感到担心,但了解GC的算法可以帮助你更好地设计你的应用程序。 –