Can this go into deadlock scenario?
No.
Should we use same lock1 in both methods ?
Yes. You should always lock on the same lock object when accessing a particular object on multiple threads. In your specific case the code you've shown is completely wrong and broken. You should have one lock per list, and consistently take out that lock every time you access the list.
If you are updating the list variable then same thing -- you should have one lock for the list variable, and every single time you access the variable for any reason needs to be under that lock.
Reason for using two different locks is that removal happens from various tasks running in parallel but updating the list happens from new thread running every few seconds.
That doesn't matter. All updates, whether they are removals or otherwise, must happen under the same lock.
If you are in a situation where you have many frequent readers and few writers, there are special-purpose locks for those cases. But that is not your scenario.
Some questions you did not ask:
What causes a deadlock?
void Transfer(Account a1, Account a2, decimal amount)
{
lock(a1)
{
lock(a2)
{
// do the transfer
}
}
}
Suppose thread X calls Transfer(savings, checking, 100)
and gets as far as locking savings
. Then we switch to thread Y which calls Transfer(checking, savings, 50)
. We lock checking
, and then attempt to lock savings
, but cannot, because X has it. We then switch back to X, which tries to lock checking
, but cannot, because Y has it. We then wait forever. That's a deadlock.
Does locking the same object "nested" on the same thread cause a deadlock?
No. The answer which says that is wrong. Taking a lock you already have on the thread automatically succeeds.
Are there better techniques I should be using?
Yes. Multithreaded programs are hard to write correctly. If you must, use high-level objects such as multithreaded collections or immutable collections that are designed to solve these problems efficiently without explicit locks.
You should also read
Confusion about the lock statement in C#