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)