Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 71969
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T19:58:16+00:00 2026-05-10T19:58:16+00:00

The MSDN documentation says that public class SomeObject { public void SomeOperation() { lock(this)

  • 0

The MSDN documentation says that

public class SomeObject {   public void SomeOperation()   {     lock(this)     {       //Access instance variables     }   } } 

is "a problem if the instance can be accessed publicly". I’m wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T19:58:16+00:00Added an answer on May 10, 2026 at 7:58 pm

    It is bad form to use this in lock statements because it is generally out of your control who else might be locking on that object.

    In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.

    A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using this violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on this unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.

    Finally, there is the common misconception that lock(this) actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is false. The object passed as a parameter to lock merely serves as a key. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.

    This is why it’s bad to use strings as the keys in lock statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an Object instance will do nicely.

    Run the following C# code as an example.

    public class Person {     public int Age { get; set;  }     public string Name { get; set; }      public void LockThis()     {         lock (this)         {             System.Threading.Thread.Sleep(10000);         }     } }  class Program {     static void Main(string[] args)     {         var nancy = new Person {Name = 'Nancy Drew', Age = 15};         var a = new Thread(nancy.LockThis);         a.Start();         var b = new Thread(Timewarp);         b.Start(nancy);         Thread.Sleep(10);         var anotherNancy = new Person { Name = 'Nancy Drew', Age = 50 };         var c = new Thread(NameChange);         c.Start(anotherNancy);         a.Join();         Console.ReadLine();     }      static void Timewarp(object subject)     {         var person = subject as Person;         if (person == null) throw new ArgumentNullException('subject');         // A lock does not make the object read-only.         lock (person.Name)         {             while (person.Age <= 23)             {                 // There will be a lock on 'person' due to the LockThis method running in another thread                 if (Monitor.TryEnter(person, 10) == false)                 {                     Console.WriteLine(''this' person is locked!');                 }                 else Monitor.Exit(person);                 person.Age++;                 if(person.Age == 18)                 {                     // Changing the 'person.Name' value doesn't change the lock...                     person.Name = 'Nancy Smith';                 }                 Console.WriteLine('{0} is {1} years old.', person.Name, person.Age);             }         }     }      static void NameChange(object subject)     {         var person = subject as Person;         if (person == null) throw new ArgumentNullException('subject');         // You should avoid locking on strings, since they are immutable.         if (Monitor.TryEnter(person.Name, 30) == false)         {             Console.WriteLine('Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \'Nancy Drew\'.');         }         else Monitor.Exit(person.Name);          if (Monitor.TryEnter('Nancy Drew', 30) == false)         {             Console.WriteLine('Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!');         }         else Monitor.Exit('Nancy Drew');         if (Monitor.TryEnter(person.Name, 10000))         {             string oldName = person.Name;             person.Name = 'Nancy Callahan';             Console.WriteLine('Name changed from '{0}' to '{1}'.', oldName, person.Name);         }         else Monitor.Exit(person.Name);     } } 

    Console output

    'this' person is locked! Nancy Drew is 16 years old. 'this' person is locked! Nancy Drew is 17 years old. Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string 'Nancy Drew'. 'this' person is locked! Nancy Smith is 18 years old. 'this' person is locked! Nancy Smith is 19 years old. 'this' person is locked! Nancy Smith is 20 years old. Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining! 'this' person is locked! Nancy Smith is 21 years old. 'this' person is locked! Nancy Smith is 22 years old. 'this' person is locked! Nancy Smith is 23 years old. 'this' person is locked! Nancy Smith is 24 years old. Name changed from 'Nancy Drew' to 'Nancy Callahan'. 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 182k
  • Answers 182k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You should rewrite your code: public static Image LoadImage(string filename)… May 12, 2026 at 4:28 pm
  • Editorial Team
    Editorial Team added an answer Congratulations on spotting the mistake in the documentation :-) The… May 12, 2026 at 4:28 pm
  • Editorial Team
    Editorial Team added an answer You can use WriteXml to write to a stream: byte[]… May 12, 2026 at 4:28 pm

Related Questions

I have a method which takes a directory path as a string. In the
In the MSDN documentation, it says it returns just directory names(Return Value Type: ...
Reading msdn documentation for dictionaries it says : Public static (Shared in Visual Basic)
The MSDN documentation indicates that this API is not limited to Windows Mobile, but

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.