Custom Page member

T

Tumurbaatar S.

Hi!
The situation is:
1. In Page_Load, I open a database connection which is closed on handler
finish.
2. In Button_Click, I do same thing again as above.

So during one request, a db connection opens/closes 2 times. I think this is
not normally
and now I added to my page class a 'private SqlConnection MyConn'. Both
above 2 handlers
check whether this field is null and creates/opens the connection. Am I
doing right?
This is a standard technique of ASP.NET for such situations?
Also, what event occurs early, Page_Load or Button_Click?

Thanks!
 
J

jasonkester

Actually, you're probably better off doing it the first way you
describe. Database connections work best if you open and close them in
a single block of code. Ideally, wrapped in a using(){} block.

If you try to manage a private connection, you run the risk of leaving
it open or referenced by something that stays alive longer that you
expected. This leads to leaky code (which is still very possible in
C#), which will cause you much more trouble than the occasional page
opening and closing two connections to the database.

Good luck!

Jason Kester
Expat Software Consulting Services
http://www.expatsoftware.com/
 
T

Tumurbaatar S.

After debugging my first ASP.NET app, I found
that Page.Load event occurs before Button_Click and
Page.Unload raised at the end. So I placed a connection
close code within Unload. But can I be sure that Page.Unload
will be called in any situation?
 
J

jasonkester

In theory.

All I can tell you is that I've spent loads of time tracking down
ConnectionPool exceptions in other people's code. There's a dozen ways
for your connections to get left open if you're not on top of them. In
a web app that you expect to have running for weeks at a time, they'll
pile up on you and you'll start seeing strange exceptions.

In my code, database connections and transactions always live in a
using block, and open/close statements are always within a few lines of
eachother. I've never had any leaks from this practice.


Jason Kester
Expat Software Consulting Services
http://www.expatsoftware.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top