I've got myself very confused, and I wonder if you guys can help a
little bit.

In my data-layer, I'm trying to implement some caching for a long (well
2-3 seconds) running database operation.  I know when the results would
have changed, so when to re-run the stored proc.  The stored proc takes
some parameters which varies the output.  So I need to have a hashtable
of results.  It needs to be thread-safe.

Here's the non-cached version.  GetListLong would actually execute the
stored proc.

  DataTable GetList(int a, int b, int c) {
        return GetListLong(a, b, c);
  }

Here's a version which looks good:

  Hashtable ht = new Hashtable();

  public DataTable GetList(int a, int b, int c)
  {
    lock (ht.SyncRoot)
    {
          HashKey key = new HashKey(a,b,c);
        DataTable dt = (DataTable)ht[key];
          if (Expired(dt) == true) {
                dt = GetListLong(a,b,c);
            ht[key] = dt;
          }
        if (dt == null)
        {
            dt = GetListLong(a, b, c);
            ht.Add(key, dt);
        }
    }

    return dt;
}

But, I can see this would not be particularly fast, since only a single
reader would be allowed into the code loop.

What I really want to do is allow multiple users to read, AND multiple
calls to GetListLong - as long as the parameters are different (if there
is one already executing, wait for that to finish and get the results) -
but, of course, add to the hashtable with thread safety.

I'm sure there must be a really elegant way to do this. Any hints?

===================================
This list is hosted by DevelopMentorŪ  http://www.develop.com
Some .NET courses you may be interested in:

NEW! Guerrilla ASP.NET, 17 May 2004, in Los Angeles
http://www.develop.com/courses/gaspdotnetls

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to