473,763 Members | 7,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cache Issues

Hi,

I'm retriving data from a database and storing it on the Cache Object using
the following code:

HttpContext.Cur rent.Cache.Inse rt(
cacheItemKey,
contentDS, //THE DATASET WITH MY DATA
null,
DateTime.Now.Ad dSeconds(600),
TimeSpan.Zero
);

It works fine but I'm having a strange behaviour I cannot find the cause:

I click around the site to test the speed and the usage of the cache (using
TRACE).

I get to different results at random (from my trace):

1 loaded from cache 2.251844
this is TOO LONG since the other times I get:

1 loaded from cache 0.002361
Nothing changes but for some reason, suddenly the operation that takes 0.002
seconds decide to take 2.25 seconds.

In both instances the data is being loaded from the cache, otherwise my
trace would output "loaded from resource".

Any ideas?

Thanks,
Fernando

Nov 18 '05 #1
13 1787
Is there anything else happening on the server to cause latency?
Perhaps you could show us the code..

--
Scott
http://www.OdeToCode.com/blogs/scott/

On Sat, 23 Oct 2004 21:20:33 -0700, "Fernando Chilvarguer"
<fe******@nospa m-impex.com> wrote:
Hi,

I'm retriving data from a database and storing it on the Cache Object using
the following code:

HttpContext.Cu rrent.Cache.Ins ert(
cacheItemKey ,
contentDS, //THE DATASET WITH MY DATA
null,
DateTime.Now.A ddSeconds(600),
TimeSpan.Zer o
);

It works fine but I'm having a strange behaviour I cannot find the cause:

I click around the site to test the speed and the usage of the cache (using
TRACE).

I get to different results at random (from my trace):

1 loaded from cache 2.251844
this is TOO LONG since the other times I get:

1 loaded from cache 0.002361
Nothing changes but for some reason, suddenly the operation that takes 0.002
seconds decide to take 2.25 seconds.

In both instances the data is being loaded from the cache, otherwise my
trace would output "loaded from resource".

Any ideas?

Thanks,
Fernando


Nov 18 '05 #2
Hi Fernando,

As for the problem you mentioned, I think generally the cache data's
loading behavior should be the same during the cached object's lifecycle.
Is the problem you mentioned in the same place(in the same page's code
where you load the cache object) or in different place? In addition, would
you provide the detailed code how to trace the time when your application
loading the data from cache?
If you have any other findings, please also feel free to post here. Thanks.
Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #3
Hi Steven,

The problem occurs on different pages. All pages are accessing the same
cache functions I created.
The behavior is random. So I test "page 1" and I get the different behavior,
then I test "page 2" and I get the same interesting behavior.
In other words, sometimes the cache takes over 2 seconds to return the data,
sometimes it takes 0.002 seconds.
I made sure I stopped any process in the machine that could influence the
result by sudenlly acting on the background (such as ActiveSync, print
Spooler, etc.).
(WinXP Pro, .Net 1.1 VS 2003)

Here's the code.

1. I created a delegate function:

public delegate object CacheLoader(str ing cacheItemKey);

2. Then I created the Method implementing Cache Loading Pattern

public static object GetCacheItem(st ring cacheItemKey, CacheLoader
anyCacheLoader)
{
HttpContext context = HttpContext.Cur rent;
// acquire local reference of cache item
object cacheItem = context.Cache[cacheItemKey];
// if local reference is null, load the cache
if (cacheItem==nul l)
{
#region Load from CacheLoader delegate
cacheItem = anyCacheLoader( cacheItemKey);
// trace
context.Trace.W arn(cacheItemKe y + " loaded from resource");
#endregion
}
else
{
// trace
context.Trace.W arn(cacheItemKe y + " loaded from cache");
}
// return
return cacheItem;
}

3. This is the method that retrieves the data

public static object GetPageContent( string cacheItemKey)
{
#region Create connection to SQL Server
SqlConnection myConn;
string sConnString = "";
sConnString = "SERVER=" + ConfigurationSe ttings.AppSetti ngs["sServer"] +
ETC....
myConn = new SqlConnection(s ConnString);
try
{
myConn.Open();
}
catch
{
....
}
#endregion
string sqlstr = "select * from XXX where WWW_Status = 1 AND Page_ID=" +
cacheItemKey + " order by Content_OrderBy ";
SqlCommand myCommand = new SqlCommand(sqls tr,myConn);
SqlDataAdapter myDA = new SqlDataAdapter( );
myDA.SelectComm and = myCommand;
DataSet contentDS = new DataSet();
myDA.Fill(conte ntDS, "Content");

#region Insert into Cache with absolute expiration
HttpContext.Cur rent.Cache.Inse rt(
cacheItemKey,
contentDS,
null,
DateTime.Now.Ad dSeconds(600),
TimeSpan.Zero);
#endregion
return contentDS;
}

4. This is how I call everything from the page:

public DataSet getGenericConte nt(string strPageID)
{
DataSet contentDS = (DataSet)CacheL oaders.GetCache Item(strPageID, new
CacheLoader(Cac heLoaders.GetPa geContent));
return contentDS;
}

It all works great with the exception of this weird behavior.

THANK YOU for any help.

Fernando
"Steven Cheng[MSFT]" <v-******@online.m icrosoft.com> wrote in message
news:NY******** ******@cpmsftng xa10.phx.gbl...
Hi Fernando,

As for the problem you mentioned, I think generally the cache data's
loading behavior should be the same during the cached object's lifecycle.
Is the problem you mentioned in the same place(in the same page's code
where you load the cache object) or in different place? In addition,
would
you provide the detailed code how to trace the time when your application
loading the data from cache?
If you have any other findings, please also feel free to post here.
Thanks.
Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Nov 18 '05 #4
Hi Fernando,

Thanks a lot for your detailed response and the code snippet. I've got the
things you've done. From the code , you're writing trace everytime when you
finished retrieving data from the cache....

Currently I think you can try the following things:
1. Since the loading time we care about is during the following sentense:

object cacheItem = context.Cache[cacheItemKey];

that's the code which retrieve datas from the ASP.NET's cache collection.
So I suggest you put some code to write out the current dateTime string(via
System.DateTime .Now) into trace before and after that line of code so as to
see whether the period of time is about the same. Such as :

if(Cache[key] != null)
{
Trace.Write(cur rent time...)
object cacheItem = context.Cache[cacheItemKey];
Trace.Write(cur rent time..)

}

2. Also, you may add some further tracing code in where it may be in the
execute path at runtime when we retrieve data from trace. Thus, we can
check whether they're always going through the same execute path when we
got different period of time(it load data from cache).

Also, if you have anyother ideas, please feel free to let me know. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Nov 18 '05 #5
Hi Steve,
Thank again for being such a great helper.

Here's the follow-up to your sugestion:

I ended up putting trace stuff everywhere and found the offending statement:

I was opening a connection to the database independent of getting the data
from the cache or from the DB.

I fixed that and now a connection is open ONLY when the data needs to be
loaded from the DB and not from the cache.

Of course, that created another question in my mind:

Why would opening a DB connection be fast sometimes and slow other times?
Shouldn't the time to open a DB connection be consistent? What am I missing?

The statement is:

SqlConnection myConnection;
string sConnString = "SERVER=" +
ConfigurationSe ttings.AppSetti ngs["sServer"] .....
myConnection= new SqlConnection(s ConnString);
try
{
myConnection.Op en();
}

Sometimes is takes 0.002 seconds, sometimes it takes over 2 seconds.

Any ideas?

Thanks,
Fernando

"Steven Cheng[MSFT]" <v-******@online.m icrosoft.com> wrote in message
news:u5******** ******@cpmsftng xa10.phx.gbl...
Hi Fernando,

Thanks a lot for your detailed response and the code snippet. I've got the
things you've done. From the code , you're writing trace everytime when
you
finished retrieving data from the cache....

Currently I think you can try the following things:
1. Since the loading time we care about is during the following sentense:

object cacheItem = context.Cache[cacheItemKey];

that's the code which retrieve datas from the ASP.NET's cache collection.
So I suggest you put some code to write out the current dateTime
string(via
System.DateTime .Now) into trace before and after that line of code so as
to
see whether the period of time is about the same. Such as :

if(Cache[key] != null)
{
Trace.Write(cur rent time...)
object cacheItem = context.Cache[cacheItemKey];
Trace.Write(cur rent time..)

}

2. Also, you may add some further tracing code in where it may be in the
execute path at runtime when we retrieve data from trace. Thus, we can
check whether they're always going through the same execute path when we
got different period of time(it load data from cache).

Also, if you have anyother ideas, please feel free to let me know. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #6
Hi Fernando:

I'm just throwing this out as an idea until Steve gets back to you.

I can picture why this would happen with connection pooling enabled
(which it is enabled by default). Sometimes the app will ask for a
connection and one is waiting and available in the pool. Other times
the app might ask for a connection and there are no free, open
connections in the pool so the runtime needs to open another
connection with the database server.

Going back up a few posts I noticed the code snippet posted does not
appear to be closing the connection. This has to happen as soon as
possible to keep free connections in the pool. One easy method is to
keep the connection in a using clause:

using(SqlConnec tion connection = new SqlConnection(< cstring>))
{
// ...
}

This ensure the connection is properly disposed even when an exception
occurs.

HTH.

--
Scott
http://www.OdeToCode.com/blogs/scott/

On Wed, 03 Nov 2004 03:32:25 GMT, "Fernando Chilvarguer"
<fe******@nospa mimpex.com> wrote:
Hi Steve,
Thank again for being such a great helper.

Here's the follow-up to your sugestion:

I ended up putting trace stuff everywhere and found the offending statement:

I was opening a connection to the database independent of getting the data
from the cache or from the DB.

I fixed that and now a connection is open ONLY when the data needs to be
loaded from the DB and not from the cache.

Of course, that created another question in my mind:

Why would opening a DB connection be fast sometimes and slow other times?
Shouldn't the time to open a DB connection be consistent? What am I missing?

The statement is:

SqlConnectio n myConnection;
string sConnString = "SERVER=" +
ConfigurationS ettings.AppSett ings["sServer"] .....
myConnection = new SqlConnection(s ConnString);
try
{
myConnection.O pen();
}

Sometimes is takes 0.002 seconds, sometimes it takes over 2 seconds.

Any ideas?

Thanks,
Fernando


Nov 18 '05 #7
Great ideas , Scott,

Hi Fernando,

I think Scott's explanation on the ConnectionPool make much sense. This is
a default option of the ADO.NET uses which may help reuse the existing
connections. Also, there're many available confige arguments we can set for
adjusting the connection pool(via connection string). And the detailed
mechasim are also different according to the end DBMS or the data access
level, here are some tech articles discussing on this:
#The .NET Connection Pool Lifeguard
http://msdn.microsoft.com/library/de...us/dnsqlmag03/
html/The_NETConnecti onPoolLifeguard .asp

#Pooling in the Microsoft Data Access Components
http://msdn.microsoft.com/library/en...asp?frame=true

Hope also helps. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #8
Steve, Scott,

Thanks!! You were both right.
I used the performance monitor to check my connections and I was leaving
some connections open which I think was the reason for my problem
(ironically, absolutly nothing to do with caching!).

Of course, this opened an even bigger can of worms for me. I'll try to make
a long story short:

1. I always thought that the expensive operation was the "connection.ope n()"
so I would open the connection, do whatever I had to do, use that same
connection many times and just close it at the end, trying to avoid many
"opens" and "closes". Now I realise that's the wrong way and I should open a
connection, use it, and close it as soon as possible. There will be no
performance penalty since there's a managed pool.

2. Coming from regular ASP and ADO, I built the majority of my code around
SQLDataReaders, which now I understand, is a "connected" object. It seems
that I'll have to change all my data access methods to use DataSets insted.
(fyi, I do all my data updates "manually" via SQL)

Question:

The DataSet is a "heavier" object, with a bigger footprint. Will there be
any performace issues with that? Isn't it overkill to use a DataSet just to
use the functionality available on the DataReader? All I need is to retrive
the data and read it once.

the current code (which does not work because the reader is closed before
it's returned):

public SqlDataReader loadMemberById( string strMemberID)
{
using(SqlConnec tion myConn = new SqlConnection(s ConnString))
{
string sqlstr = "select * from TABLE where MemberID ='" +
strMemberID + "'";
SqlCommand myCommand = new SqlCommand(sqls tr,myConn);
SqlDataReader myReader = myCommand.Execu teReader();
return myReader;
}
}

Is there any way to avoid using a DataSet in this scenario?

Once again, many thanks!!!

Fernando

"Steven Cheng[MSFT]" <v-******@online.m icrosoft.com> wrote in message
news:2c******** ******@cpmsftng xa10.phx.gbl...
Great ideas , Scott,

Hi Fernando,

I think Scott's explanation on the ConnectionPool make much sense. This is
a default option of the ADO.NET uses which may help reuse the existing
connections. Also, there're many available confige arguments we can set
for
adjusting the connection pool(via connection string). And the detailed
mechasim are also different according to the end DBMS or the data access
level, here are some tech articles discussing on this:
#The .NET Connection Pool Lifeguard
http://msdn.microsoft.com/library/de...us/dnsqlmag03/
html/The_NETConnecti onPoolLifeguard .asp

#Pooling in the Microsoft Data Access Components
http://msdn.microsoft.com/library/en...asp?frame=true

Hope also helps. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #9
Hi Fernando:

Something you could do is use CommiandBehavio r.CloseConnecti on when
you open the data reader. When you close the reader then, the
connection is also closed. i.e.:

reader= myCommand.Execu teReader(Comman dBehavior.Close Connection);

and sometime later

reader.Close(); // connection also closed

That would allow you to still return the reader from a function, but
you still need to take great care to close the reader!

--
Scott
http://www.OdeToCode.com/blogs/scott/

On Fri, 05 Nov 2004 18:57:18 GMT, "Fernando Chilvarguer"
<fe******@nospa mimpex.com> wrote:
Steve, Scott,

Thanks!! You were both right.
I used the performance monitor to check my connections and I was leaving
some connections open which I think was the reason for my problem
(ironically, absolutly nothing to do with caching!).

Of course, this opened an even bigger can of worms for me. I'll try to make
a long story short:

1. I always thought that the expensive operation was the "connection.ope n()"
so I would open the connection, do whatever I had to do, use that same
connection many times and just close it at the end, trying to avoid many
"opens" and "closes". Now I realise that's the wrong way and I should open a
connection, use it, and close it as soon as possible. There will be no
performance penalty since there's a managed pool.

2. Coming from regular ASP and ADO, I built the majority of my code around
SQLDataReaders , which now I understand, is a "connected" object. It seems
that I'll have to change all my data access methods to use DataSets insted.
(fyi, I do all my data updates "manually" via SQL)

Question:

The DataSet is a "heavier" object, with a bigger footprint. Will there be
any performace issues with that? Isn't it overkill to use a DataSet just to
use the functionality available on the DataReader? All I need is to retrive
the data and read it once.

the current code (which does not work because the reader is closed before
it's returned):

public SqlDataReader loadMemberById( string strMemberID)
{
using(SqlConnec tion myConn = new SqlConnection(s ConnString))
{
string sqlstr = "select * from TABLE where MemberID ='" +
strMemberID + "'";
SqlCommand myCommand = new SqlCommand(sqls tr,myConn);
SqlDataReader myReader = myCommand.Execu teReader();
return myReader;
}
}

Is there any way to avoid using a DataSet in this scenario?

Once again, many thanks!!!

Fernando

"Steven Cheng[MSFT]" <v-******@online.m icrosoft.com> wrote in message
news:2c******* *******@cpmsftn gxa10.phx.gbl.. .
Great ideas , Scott,

Hi Fernando,

I think Scott's explanation on the ConnectionPool make much sense. This is
a default option of the ADO.NET uses which may help reuse the existing
connections. Also, there're many available confige arguments we can set
for
adjusting the connection pool(via connection string). And the detailed
mechasim are also different according to the end DBMS or the data access
level, here are some tech articles discussing on this:
#The .NET Connection Pool Lifeguard
http://msdn.microsoft.com/library/de...us/dnsqlmag03/
html/The_NETConnecti onPoolLifeguard .asp

#Pooling in the Microsoft Data Access Components
http://msdn.microsoft.com/library/en...asp?frame=true

Hope also helps. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Nov 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
14229
by: Alex | last post by:
Hi all, We're looking at a vendor who uses the InterSystems Cache Database Platform, but our IT department has zero experience with this system. This software package will have a pivotal and mission critical roll in our organization, so I'd like some comments on what others think of this database platform. Mainly I'm curious how easy/difficult it is to query a Cache Database, and does it use standard SQL calls like Oracle and MS SQL? ...
17
4833
by: emerth | last post by:
Hello all: I have read references to optimizing C code to exploit the CPU cache of <insert your favourite CPU>. Can anyone point me towards some info on the 'net that gets into techniques for this kind of thing in C (or C++) in some depth? I imagine this can get specific to the CPU in question.
1
2724
by: William Sullivan | last post by:
I'm trying to nail down some issues with the cache in my application. Currently, I have an object that stands between my business logic and database logic called CacheLogic (cute, no?). Global.asax.cs creates it in Application_Start, initializes it and places it in the cache. During initialization, CacheLogic retrieves data from the DB logic layer and caches it with removal callbacks set. Whenever an object in the business logic layer...
17
4243
by: StevePBurgess | last post by:
A really simple script is driving me up the wall. I have a very simply facility on a website to allow the user to reorder items in a database table as she wishes by clicking a link that (in this case) says "MOVE UP" and links to the script below. This script snippet that does all the work is shown - the database connection is established and after doing its work the script returns the user to the referring page.
5
2279
by: J055 | last post by:
Hi The following code works on my develeopment machine using the VS web server. When I run the application on 2 other Windows 2003/IIS 6 servers no caching seems to take place at all. Can someone explain what I might be doing wrong or what to look out for? What's the differece between IIS and VS web server? The IIS servers seem to have enough memory. public DataTable GetAll() {
10
1864
by: =?Utf-8?B?TWFyaw==?= | last post by:
Hi... We've been trying to migrate our asp.net apps off older, underpowered hardware to newer, bigger boxes but when we do, we see our databases start to melt. When I started to look into it, I found that the older boxes all had bigger EffectivePrivateBytesLimit values than the newer boxes, which seems very counter-intuitive to me. And it seemed to me that a much smaller Cache would be pushing more requests back to the databases.
1
1228
by: WT | last post by:
Hello, I have a dictionary made with objects which contain a control element, the control element is added to a Page when I want to edit the dictionary content. I put this dictionary in cache to improve ovaral speed. But I am using Ajax.Net and somme of my controls are registering script with the scrip manager on the PreRender stage of the control and it appears that the control elements, when saving the dictionary in cache, are also...
2
1840
by: Ken Fine | last post by:
I have a question about ASP.NET output caching. I want to use screen scraping as a temporary hack to pull in some complex Classic ASP-rendered content into some ASP.NET pages: protected String ReadHtmlPage(string url) { WebResponse objResponse; WebRequest objRequest = System.Net.HttpWebRequest.Create(url); objResponse = objRequest.GetResponse();
7
2014
by: Andrew Jocelyn | last post by:
Hi I'm running an ASP.NET web application under IIS. I'm inserting a cache object with a file based CacheDependency. I've noticed that when the file changes the Cache object is not always immediately invalidated. e.g. Cache.Insert("myobj", data, new CacheDependency(filePath)); When I make a change to the file 'filePath' and call the object from the cache it is not null. I'm disposing of the FileStream object immediately
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9937
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.