问题描述
在我的 asp.net
应用程序,我想缓存一些数据,在对HttpApplicationState
。
我的code设置数据看起来是这样的:
Application.Lock();
Application.Set(名称,值);
Application.UnLock();
当我阅读文档,它说,对HttpApplicationState
被隐线程安全的。但在许多博客它写,我们应该用 Application.Lock()
和 Application.Unlock()
写入数据到对HttpApplicationState
。
在另一方面,我找不到任何文档它说,我们应该使用锁,而从对HttpApplicationState
或在清除它读取数据(使用 Application.RemoveAll()
)的方法。
我的问题是:
- 我们不应该照顾线程安全的,当我们呼吁
removeall过
?在我的应用程序,它可能是一个线程正在读对HttpApplicationState
数据,而其他的线程可以调用removeall过
。 - 在这种情况下,阅读和结算时,
对HttpApplicationState
可以从两个不同的线程在同一时间,应该读得不是线程安全的?
您只需要输入锁,如果你正在做一个以上的操作对应用程序的状态。在你如果你只是在做一个操作,所以它是绝对安全的无锁:
Application.Set(名称,值);
如果你做一个以上的操作,他们互相依赖,你需要的锁。例如:
Application.Lock();
字符串名称= Application.Get(姓名);
如果(名称== NULL){
Application.Set(名称,值);
}
Application.UnLock();
In my asp.net
application, i want to cache some data in the HttpApplicationState
.
My code to set the data looks like this:
Application.Lock();
Application.Set("Name", "Value");
Application.UnLock();
When I read the documentation, it says that HttpApplicationState
is implicitly thread safe. But on many blogs it's written that we should use Application.Lock()
and Application.Unlock()
while writing data to the HttpApplicationState
.
On the other hand, I could not find any documentation which says that we should use lock while reading data from HttpApplicationState
or while clearing it (using Application.RemoveAll()
) method.
My questions are:
- Should not we take care of thread-safety when we are calling
RemoveAll
? In my application, it's possible that one thread is reading a data fromHttpApplicationState
whereas other thread could callRemoveAll
. - In this case when reading and clearing
HttpApplicationState
is possible from two different threads at the same time, should reading too not be thread safe?
You only need the lock if you are doing more than one operation against the application state. In you case you are just doing one operation, so it's perfectly safe without the lock:
Application.Set("Name", "Value");
If you do more than one operation, and they rely on each other, you need the lock. For example:
Application.Lock();
string name = Application.Get("Name");
if (name == null) {
Application.Set("Name", "Value");
}
Application.UnLock();
这篇关于是HttpApplicationState.RemoveAll()线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!