ReaderWriterLock VS锁定{}ReaderWriterLock、VS

2023-09-02 20:45:21 作者:子孤夜吟

请解释一下什么是主要的区别,当我应该用什么。 在注重网络的多线程应用程序。

Please explain what are the main differences and when should I use what. The focus on web multi-threaded applications.

推荐答案

锁定只允许一个线程在同一时间执行code。 ReaderWriterLock可以允许多个线程来读取在同一时间或具有用于写入独占访问,所以它可能是更有效的。如果您使用的是.NET 3.5 ReaderWriterLockSlim甚至更快。所以,如果您的共享资源被读取比被写入更多的时候,使用 ReaderWriterLockSlim 。一个很好的例子,使用它,你经常阅读(对每个请求),你很少更新文件的内容的文件。所以,当你从文件中读取您输入一个读锁定使许多请求可以打开阅读,当你决定写你进入一个写锁。使用上的文件锁定将基本上意味着你可以成为一次一个请求。

lock allows only one thread to execute the code at the same time. ReaderWriterLock may allow multiple threads to read at the same time or have exclusive access for writing, so it might be more efficient. If you are using .NET 3.5 ReaderWriterLockSlim is even faster. So if your shared resource is being read more often than being written, use ReaderWriterLockSlim. A good example for using it is a file that you read very often (on each request) and you update the contents of the file rarely. So when you read from the file you enter a read lock so that many requests can open it for reading and when you decide to write you enter a write lock. Using a lock on the file will basically mean that you can serve one request at a time.