Learning ASP. NET MVC5 framework secrets notes-ASP. NET routing (8), mvc5-asp.net
6. Thread Security
The RouteCollection object represented by Routes, the static read-only attribute of RouteTable, is the global route table for the entire application. This collection object itself does not provide thread security guarantee, so simultaneous operations on the same RouteCollection object in multiple threads may cause unexpected concurrency problems. To solve this problem, the following two methods (GetReadLock and GetWriteLock) are defined in the RouteCollection type. We can call them to obtain the Read and Write locks when reading or updating the set.
When the GetReadLock method is executed, the read lock of the set is returned only when the write lock of the current RouteCollection object is not obtained. Otherwise, the lock is released. When we call the GetWriteLock method view to obtain the write lock of A RouteCollection object, the write lock for this set is returned only when no thread has a read lock or write lock, otherwise, all locks will be released. That is to say, the RouteCollection object in the thread security state can be read by multiple threads at the same time, but cannot be read by another thread at the same time. A set can only be updated by one thread at a time. At this time, reading and updating data from other threads for the set is not allowed.
The GetReadLock and GetWriteLock return types of RouteCollection are all IDisposable interfaces. In fact, the returned values are two private types embedded in RouteCollection (ReadLockDisposable and WriteLockDisposable ), they implement the read/write lock function through the encapsulated RouterWriterLockSlim object. ReadLockDisposable and WriteLockDisposable implement the IDisposable interface and release the lock in the Dispose method. Therefore, the recommended programming method is as follows.
// Read using (IDisposable readLock = routeCollection. getReadLock () {// read RouteCollection} // write operation using (IDisposable writeLock = routeCollection. getWriterLock () {// update RouteCollection}
The essence of Route registration is to create a corresponding Route object and add it to the global Route table represented by Routes, the static attribute of RouteTable. It should be said that no matter whether we call the RouteCollection Add method or MapPageRoute, we need to get the write lock of the set in advance, but in general, the registration of the route occurs when the application starts (the request has not arrived yet ), it can ensure that the collection object will be operated by only one single thread at this time, so in this case we do not need to call the GetWriteLock method. It is worth mentioning that the GetRouteData and GetVirtualPath methods of RouteCollection have called the GetReadLock method to obtain the read lock before traversing the set. Therefore, these two methods are thread-safe.