嗯,我的意思是我有几段代码使用了我想要保护的一些变量。 但其想法是多个线程只读取该变量。 并且只有一个线程正在向其写入数据,而且写入的频率并不高。 我希望能够让多个线程同时进行读取,并且仅在写入线程访问该变量时才锁定该变量。
如果我使用普通的 lock(variable){} 构造,那么所有读取线程将相互阻塞。 那么有没有办法做到这一点?
最佳答案
听起来您正在寻找 ReaderWriterLock类。
ReaderWriterLock is used to synchronize access to a resource. At any given time, it allows either concurrent read access for multiple threads, or write access for a single thread. In a situation where a resource is changed infrequently, a ReaderWriterLock provides better throughput than a simple one-at-a-time lock, such as Monitor.
关于c# - 是否可以让 lock{} 或类似结构仅锁定写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736891/