1.application.lock and Application.UnLock are typically paired to lock all code between lock and unlock (note that not only the assignment to application is locked).
2.Lock (obj) is used to lock the Obj object, the Obj object must be a global object (for example: application).
How to use Application.lock/unlock:
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 two pieces of code are the same, locking the code snippet so that the code within the code snippet is not executed simultaneously by multithreading.
There's a difference between them, so look at the difference:
When any Web page in the site executes Application.Lock, all operations on application in the entire station will be locked for a delayed execution. (Includes: Application assignment and application read), while lock (obj) does not affect other pages that do not have write lock (obj).
Example:
Let's take a look at the usage of Application.Lock:
A page:
Application.Lock ();
application["value"] = 1;
System.Threading.Thread.Sleep (10000);
Application.UnLock ();
b page:
Object value = applcation["value"];
We execute the a page first and then the B page. Since application is locked in the a page, it is necessary to get the values in the application in the page B to wait for the a page to finish executing.
Let's take a look at the use of Lock (obj):
A page:
Lock (Application)
{
application["value"] = 1;
System.Threading.Thread.Sleep (10000);
}
b page:
Object value = applcation["value"];
applcation["value"] = 2;
We also execute the a page first and then the B page. You will find that the application in page A is locked, but because there is no corresponding lock code on page B, both reads and edits are successful.
If you need to lock the B page, you need to modify the B page code to:
Lock (Application)//b page is also added to the lock
{
Object value = applcation["value"];
applcation["value"] = 2;
}
In addition: Application and lock (application) Although can be locked application, but cannot lock each other , namely: in a page with Application.lock/unlock, in the B page with lock (application), so the B page is not locked, of course, if the B page itself contains the application reading and assignment, then the B page will be locked, because the above mentioned.
This shows: Application.lock/unlock is more secure because it is globally locked for all application, and lock (obj) is more flexible because another page can modify the contents of the other page lock if there is no write lock (obj) , so writing code requires us to be more serious. The bottom is to use which is better, look at your own actual needs.
About Application.Lock and lock (obj)