18.11. Optimizing Read-Mostly Access

Problem

You are operating on data that is mostly read with occasional updates and want to perform these actions in a thread-safe but efficient manner.

Solution

Use the ReaderWriterLockSlim to give multiple read/single write access with the capacity to upgrade the lock from read to write. The example we use to show this is that of a Developer starting a new project. Unfortunately, the project is under-staffed, so the Developer has to respond to tasks from many other individuals on the team by themselves. Each of the other team members will also ask for status updates on their tasks, and some can even change the priority of the tasks the Developer is assigned.

The act of adding a task to the Developer using the AddTask method is protected with a write lock using the ReaderWriterLockSlim by calling EnterWriteLock and ExitWriteLock when complete:

	public void AddTask(Task newTask)
	{
	    try
	    {
	        _rwlSlim.EnterWriteLock( );
	        // if we already have this task (unique by name)
	        // then just accept the add as sometimes people
	        // give you the same task more than once :)

	        var taskQuery = from t in _tasks
	                        where t == newTask
	                        select t;
	        if (taskQuery.Count<Task>( ) == 0)
	        {
	            Console.WriteLine("Task " + newTask.Name + " was added to developer");
	            _tasks.Add(newTask);
	        }
	    }
	    finally
	    {
	        _rwlSlim.ExitWriteLock( );
	    }
	}

When a project team member needs to know about the status of a task, they call the IsTaskDone method, which uses a read lock on the ReaderWriterLockSlim by calling EnterReadLock ...

Get C# 3.0 Cookbook, 3rd Edition 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.