How C # avoids thread deadlocks

Source: Internet
Author: User

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语句
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.