title: Thread locking vs creating a new object
body: <p>The C# lock statement allows only one thread to access an object at a time.
  In a Parallel.ForEach loop, wouldn't it be faster to create a new object (local variable) within the loop, rather than using a field variable, since that way no threads are ever blocked?
  What would be the pros/cons of each way?</p>
  
  <p>I am using the code below, it seems that creating a local var instead of using a lock on a field is slightly faster.</p>
  
  <p>nb. There are 3 email strings in the toEmails variable.</p>
  
  <pre><code>//Method 1 with lock statement takes 14092ms
  List&lt;string&gt; toEmails = getListOfToEmails();
  Object locker = new object();
  SmtpClient smtpClient = getSmtpObject();//smtpClient is used here as a field
  Parallel.ForEach(toEmails, toEmail =&gt;
  {
      string emailBody = getEmailBody(toEmail);
  
      MailMessage mailMessage = getMailMesssageObject(emailBody, toEmail);
  
      lock (locker)
      {
          smtpClient.Send(mailMessage);
      }
  });
  
  //Method 2 without lock statement (creating a new local var each iteration) takes 13947ms
  List&lt;string&gt; toEmails = getListOfToEmails();
  Parallel.ForEach(toEmails, toEmail =&gt;
  {
      SmtpClient smtpClient = getSmtpObject();//smtpClient is used here as a local var
  
      string emailBody = getEmailBody(toEmail);
  
      MailMessage mailMessage = getMailMesssageObject(emailBody, toEmail);
  
      smtpClient.Send(mailMessage);
  });
  </code></pre>