C# lock - the opportunities

Markus Freitag 3,786 Reputation points
2020-12-17T10:04:53.067+00:00

Hello,

What is the difference.
When do I need my own object?
When can I just lock the object? The list?

Is that enough if I am in the same application, and an object like a list of two or more functions could be changed?

Can someone explain it simply? Thanks in advance!

First

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object singletonLock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (singletonLock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Second

lock (LockPackageList) 
              {
                   ListPackageLabel.Add(currentPackage);
              }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,815 questions
0 comments No comments
{count} votes

Accepted answer
  1. Cheong00 3,476 Reputation points
    2020-12-17T11:58:15.787+00:00

    1) There is no practical difference as long as the LockPackageList object you choose for lock will not be disposed within the lifetime of the running code.

    Actually in your second example, the common practice is to "lock with the resource you're trying to use", so in your case you had better do lock with ListPackageLabel itself.

    2) No. You can see some .NET classes have provided .SyncRoot member for this purpose.
    3) See (1).
    4) The second code snippet is enough.

    Just want to note that "lock" statement only provide protection for synchronized access if and only if all code within your application uses lock to access that resource. So if you experience "race condition" like errors for that resource, it would be useful to check whether all code that modifies the resource are protected by lock statement.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.