15.8. Synchronizing the Reading and Writingof a Resource Efficiently

Problem

You have a resource that is shared by multiple threads. You need to provide exclusive access to this resource when a thread is writing to it. However, you do not want the overhead of providing exclusive access to this resource when multiple threads are only reading from it. You want to allow one thread to access a shared resource only if it is writing to it, but you also want to allow multiple threads to read from this resource. While multiple threads can read from a resource, a write operation cannot occur while any thread is reading from this resource.

Solution

Use the ReaderWriterLock class from the FCL. The ReaderWriterLock is optimized for scenarios where you have data that changes infrequently but needs protection for those times when it is updated in a multithreading scenario. To illustrate, the GradeBoard class represents a board where an instructor will post the grades students received from a class. Many students can read the grade board, but only the instructor can post a grade (write) to the grade board. Students will not, however, be able to read from the board while the instructor is updating it:

class GradeBoard { // make a static ReaderWriterLock to allow all student threads to check // grades and the instructor thread to post grades static ReaderWriterLock readerWriter = new ReaderWriterLock( ); // the grade to be posted static char studentsGrade = ' '; static void Main( ) { // create students ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.