读/写锁定在asp.net中一个静止无功 [英] read/write locking a static var in asp.net

查看:134
本文介绍了读/写锁定在asp.net中一个静止无功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的C#ASP.NET项目得到了一个静态变量(抽象数据类型,而不是一个原始的)。

I've got a static variable (abstract data type, not a primitive) in my C# ASP.NET project.

它将由多个线程读取,同时频繁。

It will be read by many threads, concurrently and frequently.

我要写信给它很少(相对于阅读的数量)。

I need to write to it very rarely (compared to number of reads).

什么是确保threadsaftey的最佳途径,使虽然我写它,其他线程是不读的部分写入的数据?

What is the best way of ensuring threadsaftey so that whilst im writing to it, other threads aren't reading partially-written data?

我只用过锁定,但我知道这将prevent并发读取:(

I've only ever used lock, but i understand this will prevent concurrent reads :(

感谢

推荐答案

我开始只是锁定。无可争议的锁是非常便宜的。您的可能的使用 ReaderWriterLockSlim (假设你使用.NET 3.5),但锁是简单的得到正确的。如果/当它成为一个问题优化我它

I'd start off just with lock. Uncontested locks are very cheap. You could use ReaderWriterLockSlim (assuming you're using .NET 3.5) but a lock is simpler to get right. Optimise it if/when it becomes a problem.

ReaderWriterLock 很可能的的比简单的锁 - 这不是因为快,因为它可能会,因此超薄版本:)

Straight ReaderWriterLock may well be slower than the simple lock - it's not as fast as it might be, hence the slim version :)

究竟有多频繁,你的经常呢?多少钱争你期待什么呢?您可能希望它的模型(例如模拟请求合理数量)和基准无锁定VS简单的锁定,正好看到的开销是什么。

Just how frequently do you mean by "frequently"? How much contention do you expect? You might want to model it (e.g. simulate a reasonable number of requests) and benchmark no locking vs simple locking, just to see what the overhead is.

您的可能的能够使用的lock-free的选项挥发性 - 但坦率地说我最近放弃了,由于太辛苦对于有理智的人来思考。 (这并不意味着什么,我认为它的意思。)

You may be able to use the lock-free option of volatile - but frankly I've recently given up on that as too hard for sane people to reason about. (It doesn't mean what I thought it meant.)

什么是你真正做与数据?是该类型的不可变的类型,所以一旦你掌握了正确的参考,你可以在没有任何锁定的线程安全的方式阅读?

What are you actually doing with the data? Is the type an immutable type, so once you've got the right reference, you can read in a thread-safe way without any locking?

这篇关于读/写锁定在asp.net中一个静止无功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆