hackp0int
hackp0int

Reputation: 4169

Can i use Interlocked.Increment inside lock statement?

Can I use it like I've described in the current code?

private void Increment() {
    lock(LockObject) {      
         // edit
         // ListOfObjects.Add(someInfo);
         // new edit ---> here
         ListOfObjects.Add(new SomeInfoObject() {
             Account = Interlocked.Increment(ref result),
             // ... other properties
         }
         // Interlocked.Increment(ref result);
    }
}

Upvotes: 3

Views: 1605

Answers (3)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52107

You can use it, but is redundant in this case, since nothing else is being protected by the lock block.

Take a look at this post for more info.

--- EDIT ---

OK, I see you edited the question to add something to the lock block.

In that case, it makes sense to protect this other operation, but whether it also makes sense to put Interlocked.Increment inside the lock block depends on what you are trying to accomplish.

Could you provide more context?

Upvotes: 1

Remus Rusanu
Remus Rusanu

Reputation: 294237

Yes you can, but there should be no reason to do it. Both lock and interlocked operations work only if all parties involved agreed to do the same. If one thread uses lock, expecting that nothing can change while holding the lock, and another thread one uses ICX then the ICX thread has just violated the assumptions of the first thread. If both threads agree to use lock then the use of ICX inside lock is questionable. A single statement lock that all it does is an ICX is very very unusual.

You need to post a more detailed description of the code explaining the actual problem you're trying to solve.

Upvotes: 3

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

lock is not required when you use Interlocked class.

MSDN says,

Increments a specified variable and stores the result, as an atomic operation.

Upvotes: 3

Related Questions