Editare

Partajați prin


RouteCollection.GetReadLock Method

Definition

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

public:
 IDisposable ^ GetReadLock();
public IDisposable GetReadLock ();
member this.GetReadLock : unit -> IDisposable
Public Function GetReadLock () As IDisposable

Returns

An object that manages thread safety.

Examples

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.

Remarks

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.

Applies to

See also