This documentation is archived and is not being maintained.

RouteCollection.GetReadLock Method

Provides an object for managing thread safety when you retrieve an object from the collection.

Namespace:  System.Web.Routing
Assembly:  System.Web (in System.Web.dll)

public IDisposable GetReadLock()

Return Value

Type: System.IDisposable
An object that manages thread safety.

The RouteCollection object is available to multiple processes in the application. Therefore, if you have to retrieve a route when the application is running, use the GetReadLock method in order to guarantee thread safety. By obtaining a read lock on the route collection, you make sure that the collection will not be modified while you are trying to retrieve it.

The GetReadLock method stops the thread from continuing until the lock can be acquired. If a write lock is in place, the thread waits until the update is completed and the write lock is released. The read lock on the route collection is released when the IDisposable object that is returned by this method is disposed.

If you do not use GetReadLock, you might get an error while you are reading through the RouteCollection collection. For example, suppose you loop through the objects in the RouteCollection collection to read them, without calling GetReadLock. While you are doing that, another thread from another request might call GetWriteLock and add a route to the collection. The first thread will then fail with an error.

There are two scenarios in which you do not have to call GetReadLock:

  • Public methods of the RouteCollection class such as GetVirtualPath and GetRouteData call GetReadLock internally. Therefore, you do not have to explicitly call GetReadLock when you call a public method of the RouteCollection class to retrieve data from the collection.

  • When the application is starting and is not yet processing requests, such as in the Application_Start event handler, only one thread is running. Because there are no other threads that might update the collection while you are reading it, you do not have to call GetReadLock.

The following example shows how to use the GetReadLock method when you retrieve a route while the application is running. The Using statement ensures that no matter what happens at run time when you read from the collection (whether the code completes normally or an exception is thrown) the lock will be safely released at the end of the Using code block.

.NET Framework

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.