M.kazem Akhgary
M.kazem Akhgary

Reputation: 19159

What is the Object given to Lock

I use lock to add items to list in parallel foreach as below.

        Parallel.ForEach(list, i =>
            {
                //...

                lock (LockThread)
                {
                    _asset.Add(...);
                }
            });

LockThread is a static readonly object.

What I understand was that lock makes block single threaded and will not allow multitasking there.

So why I should give it an object ? What does it do?

Why can't I just write

lock {...}

Upvotes: 0

Views: 68

Answers (3)

mrmcgreg
mrmcgreg

Reputation: 2816

For a given object the code in at most one lock statement that uses that object can execute at at time.

If you have

var obj1 = new object();
var obj2 = new object();

and then

lock (obj1) {
   // code block 1a
}

lock (obj1) {
   // code block 1b
}

lock (obj2) {
   // code block 2
}

then code block 1a and code block 2 can execute concurrently, as can code block 1b and 2. Code blocks 1a and 1b will not be able to execute at the same time. And, of course, only one thread at a time can execute code block 1a and likewise for the others.

Upvotes: 2

Orel Eraki
Orel Eraki

Reputation: 12196

When you apply lock you basically say, "From now on only 1 can use this scope" the locking taken place on block of memory that is marked as blocked so we use the most basic form that hold memory that is the object class.

lock (refrenceMemoryObject) {
    // Scope
}

You can read more about lock HERE

Upvotes: 0

Peyman
Peyman

Reputation: 3138

It depend's on object that you want to share between different thread, if the object is ThreadSafe then you don't need put in lock but for non-threadsafe should make sure only one thread access the object at same time

For example you can find the difference between Collection and ConcurrentCollection

Upvotes: 0

Related Questions