1. application. Lock and application. Unlock are usually paired to lock allCode(Do not lock the assignment to the application ).
2. Lock (OBJ) is used to lock the OBJ object. The OBJ object must be a global object (for example, application ).
Application. Lock/unlock usage:
Application. Lock ();
// Other code
Application [ " Value " ] = 1 ;
// Other code
Application. Unlock ();
How to Use lock (OBJ:
Lock (Application ){
// Other code
Application [ " Value " ] = 1 ;
// Other code
}
The functions of the above two sections of code are the same. They lock the code segment so that the code in the code segment will not be executed simultaneously by multiple threads.
There are also differences between them. Let's take a look at their differences:
When application. Lock is executed on any web page of the website, all operations related to the application on the whole site will be locked and delayed. (Including application assignment and application reading), while lock (OBJ) does not affect other pages that do not write lock (OBJ.
Example:
Let's take a look at the usage of application. Lock:
Page:
Application. Lock ();
Application [ " Value " ] = 1 ;
System. Threading. thread. Sleep ( 10000 );
Application. Unlock ();
Page B:
Object Value = applcation [ " Value " ];
We first execute page A, and then execute page B. Because the application is locked on page A, you must wait until the execution on page a is complete before obtaining the value in application on page B.
Let's take a look at the usage of lock (OBJ:
Page:
Lock (Application)
{
Application [ " Value " ] = 1 ;
System. Threading. thread. Sleep ( 10000 );
}
Page B:
Object Value = applcation [ " Value " ];
Applcation [ " Value " ] = 2 ;
We also execute page a before page B. You will find that the application on page a is locked, but the read and modification are successful because there is no lock code on page B.
To lock page B, modify the code of page B:
Lock (Application) // Add lock to page B.
{
Object Value = applcation [ " Value " ];
Applcation [ " Value " ] = 2 ;
}
In addition, both application and lock (Application) can lock the application,But cannot lock each other, That is, use application. lock/unlock: Use lock (Application) on page B. In this way, page B cannot be locked. Of course, if page B contains read and assign values to the application, the page B will also be locked because it has been mentioned above.
It can be seen that: application. lock/unlock is safer because it globally locks all applications, while lock (OBJ) is more flexible because if lock (OBJ) is not written on another page) you can modify the lock content of other pages, so we need to write the code more seriously. It depends on your actual needs.