Arashv
Arashv

Reputation: 335

Lock in multithreaded App C#

Lets say I have declared a class like this :

public class PersistableObject<TObject> where TObject : class, new()
{
    private readonly object objectLocker = new object();
    private TObject persistableObject;

    public TObject Object
    {
        get
        {
            lock (this.objectLocker)
            {
                return this.persistableObject; 
            }
        }

        set
        {
            lock (this.objectLocker)
            {
                this.persistableObject = value;
            }
        }
    }

    public bool Persist()
    {
        lock (this.objectLocker)
        {
            // Do Persist Object in file
        }
    }

    public bool Retrieve()
    {
        lock (this.objectLocker)
        {
            // Do Retrieve Object from file
        }
    }
}

This class is responsible for storing a variable of any type, persist it to a file and retrieve it from a file.

As you can see, I used the same lock (an object) to lock 4 operations :

  1. Getting the actual object
  2. Setting the actual object
  3. Persisting the object to file
  4. Retrieving the object from file

Is this the correct approach from concurrency point of view? Am I completely in the safe zone, considering that this class is used by different threads?

UPDATE :

The most important thing for me here, is only one thread should have access to the object at any given time (no matter it wants to get, set, retrieve or persist it). Considering this in mind, is it the correct approach? will any deadlocks or other nasty things happen?

Upvotes: 2

Views: 158

Answers (2)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

Define "being in the safe zone".

Imagine a piece of code executing on multiple threads using your class to

  1. read an object from a file
  2. modify that object
  3. write that object back to the file

None of the locking you do here will help making that scenario thread-safe.

Upvotes: 0

usr
usr

Reputation: 171178

Thread-safety is a property of the whole system, not of a single class or method. Individual operations on an instance of this class will execute exclusively, but maybe you require multiple operations to be atomic. The class has no way to do that.

So is it thread-safe or not? Only you can tell because only you know how the class is being used. If operations on this class are truly independent, then it is safe.

If all you had do to obtain thread-safety way to just lock every member of any class, then threading would be a simple task. Threading is complex because it touches everything in a cross-cutting manner.

Upvotes: 4

Related Questions