Thread Safety through Self-Loading Collections
page 3 of 7
by David Penton
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 31351/ 52

Demonstration

How do we use the SingleKeyLockbox collection class? What is required of the deriving class?  There are two abstract methods that need to be implemented.

Listing 5

protected abstract TPrimaryKey GetPrimaryKeyFromValue(TValue value);

GetPrimaryKeyFromValue should contain the implementation of how to retrieve the "primary key" from the value.

Listing 6

protected abstract bool TryLoadByPrimaryKey(TPrimaryKey pkey, out TValue value);

TryLoadByPrimaryKey should contain the implementation of how to retrieve the value from the "primary key."  Notice that the return value from this method is a boolean. This is used to determine whether or not this value is actually stored in the central collection. The consumer of this collection class may not want to store null values within the central collection. The expected return value is true, so consider this when implementing this method.

Listing 7

public class UserCollection : SingleKeyLockbox<string, User>
{
  protected override string GetPrimaryKeyFromValue(User user)
  {
    return user.Username;
  }
 
  protected override bool TryLoadByPrimaryKey(string username, out User user)
  {
    user = GetUserFromDatabase( username );
    if ( user != null ) return true;
 
    return false;
  }
 
  private User GetUserFromDatabase( string username )
  {
    // implementation for retrieving a user from the database
  }
}

There is one part that we could add to this…what if I want to store this in something like ASP.NET Cache? An additional property to add to this could be something like Listing 8.

Listing 8

public UserCollection Cache
{
  get
  {
    return TCache.Get("UserCollection", 240, delegate() {
        return new UserCollection();
      });
  }
}

So, when using this collection it can simply be referred to as:

Listing 9

User user = UserCollection.Cache[ username ];

View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-30 10:45:57 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search