Introduction to C #-----Threading (ii)

Source: Internet
Author: User

Content Summary:

Synchronization of multithreading, mainly used in the MethodImplAttribute class and SynchronizationAttribute class, in essence, or based on the implementation of lock.

A simple such as Xiao Ming and red Two people are the main with the bank card, two people can operate on the account, such as account balance of 1000 yuan, such as two people almost at the same time to take money 600 yuan operation.

The code is as follows: We didn't do any synchronization, let's run the code and look at the results:

The result is not correct, we have to modify the program. Introduce the MethodImplAttribute class:

You need to reference the System.Runtime.Remoting.Contexts namespace before using the MethodImplAttribute class, System.Runtime.Remoting.Contexts Namespaces contain properties that affect the behavior of the CLR during runtime, and MethodImplAttribute is a property that MethodImplAttribute a constructor of a class that takes a MethodImplOptions enumeration as its argument. The MethodImplOptions enumeration has a field synchronized, which specifies that only one thread is allowed to access this method at any one time.

Modify: Add the MethodImplAttribute tag to the withdraw () method, the code is as follows:

Correct result:

Introduction to C #-----Threading (ii)

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.