Most deadlocks are because the code allows the resource to be locked in an inconsistent manner. For example, we have to transfer funds from one account to another account. The Monitor class provides a mechanism for synchronizing access to objects. class Controls access to an object by granting an object lock to a single thread. Object locks provide the ability to restrict access to code blocks, often called critical areas. When a thread owns a lock on an object, no other thread can acquire the lock. You can also use monitor to ensure that no other thread is allowed to access the application Code section that is being executed by the lock's owner, unless another thread is executing the code using another locked object. The sample code is as follows:
public void Transer(Account accFrom, Account accTo, decimal num)
{
Monitor.Enter(accFrom);//锁定账户一
Monitor.Enter(accTo);//锁定账户二
//业务代码。。。
Monitor.Exit(accFrom);//释放账户一
Monitor.Exit(accTo);//释放账户二
}
And this time there are two threads, line Cheng and thread two try to get the same resources in different order, each thread locks one before locking two resources, and a deadlock occurs.
The solution is to lock in the code of execution. For example:
lock(this)
{
//Monitor语句
}