473,841 Members | 1,689 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about 'Using' and resources

mg
I'm migrating from VB6 and have a question about using 'Using' and the
best way to use it.

Here is a example of a small bit of code:

dbConx("open")
Using CN
Dim CMD As New OleDbCommand(sS QL, CN)
Dim DR As OleDbDataReader = CMD.ExecuteRead er()

If DR.HasRows = True Then
Dim vCID As New Collection()
While DR.Read()
vCID.Add(DR.Get Int32(0))
End While
DR.Close()
CMD.Dispose()
dbConx("close")
Else
DR.Close()
CMD.Dispose()
dbConx("close")
Return False
End If
End Using

dbConx creates an OleDbConnection CN and opens/closes it. The purpose
of this is to return 0 or more record numbers for later use. If zero
records are returned I just exit the function with a return of false.
If records found, gather them into a collection and carry on, closing
all resources used.

In VB6 I used "set x=nothing" to clean-up.

-What gets cleaned up within a 'Using' block?
-Does my CMD and DR objects get cleaned up along with CN (so not
needing all the .close and .dispose lines?
-Any cleaner way to do this?

Thanks!

Aug 31 '06 #1
10 1978
Mg,

As long as you use a form or things like that, than don't botter to much
about cleaning up.
(The dispose is in the component part of that)

VB.Net is a programming language inside the managed code group. That managed
code is special to overcome all cleaning troubles. Only unmanaged
*resources* are not cleaned up by the managed code.

In the system.data class that you show, there is not one piece of unmanaged
resource and therefore nothing of that has to be disposed by hand.

The using is quiet standard, it is using dispose consequently at the end.
That can be needed, but as I wrote not for the system.data classes.

Cor

"mg" <bi*****@gmail. comschreef in bericht
news:11******** **************@ 74g2000cwt.goog legroups.com...
I'm migrating from VB6 and have a question about using 'Using' and the
best way to use it.

Here is a example of a small bit of code:

dbConx("open")
Using CN
Dim CMD As New OleDbCommand(sS QL, CN)
Dim DR As OleDbDataReader = CMD.ExecuteRead er()

If DR.HasRows = True Then
Dim vCID As New Collection()
While DR.Read()
vCID.Add(DR.Get Int32(0))
End While
DR.Close()
CMD.Dispose()
dbConx("close")
Else
DR.Close()
CMD.Dispose()
dbConx("close")
Return False
End If
End Using

dbConx creates an OleDbConnection CN and opens/closes it. The purpose
of this is to return 0 or more record numbers for later use. If zero
records are returned I just exit the function with a return of false.
If records found, gather them into a collection and carry on, closing
all resources used.

In VB6 I used "set x=nothing" to clean-up.

-What gets cleaned up within a 'Using' block?
-Does my CMD and DR objects get cleaned up along with CN (so not
needing all the .close and .dispose lines?
-Any cleaner way to do this?

Thanks!

Aug 31 '06 #2
See inline.

mg wrote:
I'm migrating from VB6 and have a question about using 'Using' and the
best way to use it.

Here is a example of a small bit of code:

dbConx("open")
Using CN
Dim CMD As New OleDbCommand(sS QL, CN)
Dim DR As OleDbDataReader = CMD.ExecuteRead er()

If DR.HasRows = True Then
Dim vCID As New Collection()
While DR.Read()
vCID.Add(DR.Get Int32(0))
End While
DR.Close()
CMD.Dispose()
dbConx("close")
Else
DR.Close()
CMD.Dispose()
dbConx("close")
Return False
End If
End Using

dbConx creates an OleDbConnection CN and opens/closes it. The purpose
of this is to return 0 or more record numbers for later use. If zero
records are returned I just exit the function with a return of false.
If records found, gather them into a collection and carry on, closing
all resources used.

In VB6 I used "set x=nothing" to clean-up.

-What gets cleaned up within a 'Using' block?
The 'Using' keyword will automatically generate the call to Dispose at
the end of the block. The only thing you can say for certain is that
it affects the object specified in the 'Using' expression. In your
case, however, it probably disposes any OleDbCommand and
OleDbDataReader objects associated with the OleDbConnection as well.
But, that's really an implementation detail of OleDbConnection .
-Does my CMD and DR objects get cleaned up along with CN (so not
needing all the .close and .dispose lines?
I'd say probably, but it never hurts to wrap those with the 'Using'
keyword as well.
-Any cleaner way to do this?
Well, it's not clear to me what dbConx("open") does and where CN is
created. I usually create the OleDbConnection object inline with the
'Using' construct that way its scope is limited to just that block.
>
Thanks!
Aug 31 '06 #3
Cor,

See my comments inline.

Brian

Cor Ligthert [MVP] wrote:
Mg,

As long as you use a form or things like that, than don't botter to much
about cleaning up.
(The dispose is in the component part of that)

VB.Net is a programming language inside the managed code group. That managed
code is special to overcome all cleaning troubles. Only unmanaged
*resources* are not cleaned up by the managed code.

In the system.data class that you show, there is not one piece of unmanaged
resource and therefore nothing of that has to be disposed by hand.
We all know that the GC will eventually do it for us automatically when
the finalizer runs. But, the issue is with the timing of when that
happens. And I'd say it's likely that there are unmanaged resources
involved somewhere in those objects. The fact that they implement
IDisposable is a pretty good clue.
The using is quiet standard, it is using dispose consequently at the end.
That can be needed, but as I wrote not for the system.data classes.
Calling Dispose (or using the 'Using' keyword) is definitely
recommended for the classes in System.Data. If you don't then a
database connection may be held open until the GC runs and that may
take awhile.
Cor
Aug 31 '06 #4
mg
Brian Gideon wrote:
Well, it's not clear to me what dbConx("open") does and where CN is
created. I usually create the OleDbConnection object inline with the
'Using' construct that way its scope is limited to just that block.
Brian, thanks for that. CN is created in a function dbConx, just a
standard new OleDbConnection . I agree, it would be good to clearly
define its scope.

And for Cor, this example is fron a console app, not a form based app.

On a similar topic, is it better to open/close a OleDbConnection
connection as quick as possible, or is it better to create a
OleDbConnection using block around a series of OleDbCommand and
OleDbDataReader objects? By better I mean performance/resources wise.

Thanks, mg

Aug 31 '06 #5
Brian,
Calling Dispose (or using the 'Using' keyword) is definitely
recommended for the classes in System.Data. If you don't then a
database connection may be held open until the GC runs and that may
take awhile.
By whom is that recomended?

Cor

"Brian Gideon" <br*********@ya hoo.comschreef in bericht
news:11******** *************@m 79g2000cwm.goog legroups.com...
Cor,

See my comments inline.

Brian

Cor Ligthert [MVP] wrote:
>Mg,

As long as you use a form or things like that, than don't botter to much
about cleaning up.
(The dispose is in the component part of that)

VB.Net is a programming language inside the managed code group. That
managed
code is special to overcome all cleaning troubles. Only unmanaged
*resources* are not cleaned up by the managed code.

In the system.data class that you show, there is not one piece of
unmanaged
resource and therefore nothing of that has to be disposed by hand.

We all know that the GC will eventually do it for us automatically when
the finalizer runs. But, the issue is with the timing of when that
happens. And I'd say it's likely that there are unmanaged resources
involved somewhere in those objects. The fact that they implement
IDisposable is a pretty good clue.
>The using is quiet standard, it is using dispose consequently at the end.
That can be needed, but as I wrote not for the system.data classes.

Calling Dispose (or using the 'Using' keyword) is definitely
recommended for the classes in System.Data. If you don't then a
database connection may be held open until the GC runs and that may
take awhile.
>Cor

Sep 1 '06 #6
Cor,

In general, the author of the class recommends it when he/she derives
from IDisposable. So I guess that means Microsoft recommends it. One
notable exception is the DataSet. IDisposable is carried along with
MarshalByValueC omponent, but we're all pretty sure that a DataSet does
not hold unmanaged resources. But, that's not what this thread is
about. We're talking about OleDbConnection . If you choose not to call
Dispose or Close then the connection will remain open which may lead to
a bug. It's easy to demonstrate problems by creating a connection
object and calling Open in a loop repeatedly without closing or
disposing the object.

Brian

Cor Ligthert [MVP] wrote:
Brian,
Calling Dispose (or using the 'Using' keyword) is definitely
recommended for the classes in System.Data. If you don't then a
database connection may be held open until the GC runs and that may
take awhile.

By whom is that recomended?

Cor
Sep 1 '06 #7
Brian,

Who is that author of the class, I am almost sure not the leader of the
ADONET group, as far as I remember me he has written many times that closing
is more than enough for a connection in the ADONET newsgroep.

Cor

"Brian Gideon" <br*********@ya hoo.comschreef in bericht
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
Cor,

In general, the author of the class recommends it when he/she derives
from IDisposable. So I guess that means Microsoft recommends it. One
notable exception is the DataSet. IDisposable is carried along with
MarshalByValueC omponent, but we're all pretty sure that a DataSet does
not hold unmanaged resources. But, that's not what this thread is
about. We're talking about OleDbConnection . If you choose not to call
Dispose or Close then the connection will remain open which may lead to
a bug. It's easy to demonstrate problems by creating a connection
object and calling Open in a loop repeatedly without closing or
disposing the object.

Brian

Cor Ligthert [MVP] wrote:
>Brian,
Calling Dispose (or using the 'Using' keyword) is definitely
recommended for the classes in System.Data. If you don't then a
database connection may be held open until the GC runs and that may
take awhile.

By whom is that recomended?

Cor

Sep 1 '06 #8
mg,
| I'm migrating from VB6 and have a question about using 'Using' and the
| best way to use it.
Using "Using" is really about when to call Dispose.

When to call Dispose?

* Call Dispose when the type itself implements IDisposable

* Call Dispose when the type or one of its base classes *overrides*
Dispose(Boolean ) if the class inherits from System.Componen tModel.Componen t
or System.Componen tModel.MarshalB yValueComponent

* Do not explicitly call Dispose on classes deriving from
System.Windows. Forms.Control for instances placed on a
System.Windows. Forms.Form as Form will implicitly dispose of them when the
form is Disposed

* Call Dispose on System.Windows. Forms.Form objects when Form.ShowDialog is
used.

* Do not explicitly call Dispose on System.Windows. Forms.Form objects if
Form.Show is used as Dispose will be implicitly called when the form is
closed

* Do not explicitly call Dispose on classes deriving from
System.Web.UI.C ontrol as it will be implicitly called as part of the normal
ASP.NET page processing

I consider the second rule controversial as it relies on using ILDASM or
Reflector to find out implementation details of a class. Its meant for
classes such as DataSet, that have an inherited Dispose, but Dispose doesn't
really do anything.

These rules are based on private discussions with other MVPs & discussions
held in the newsgroups earlier in 2005.

These rules apply to objects that you create, explicitly or implicitly.
Objects that you "own".

Disposable Objects that are passed to you as a parameter of a method (such
as the Graphics object on the Paint event) should not have their disposed
method call, as the system calls it as part of the method that raises the
event.

Objects that something else "owns" should normally be disposed of by the
"owning" object.

Based on the above rules I would rewrite your code snippet as:

Using CN As OleDbConnection = dbConx("open")
Using CMD As New OleDbCommand(sS QL, CN)
Using DR As OleDbDataReader = CMD.ExecuteRead er()

If DR.HasRows = True Then
Dim vCID As New Collection()
While DR.Read()
vCID.Add(DR.Get Int32(0))
End While
Else
Return False
End If
End Using
End Using
End Using

Or alternatively:

Using CN As OleDbConnection = dbConx("open"), CMD As New
OleDbCommand(sS QL, CN), DR As OleDbDataReader = CMD.ExecuteRead er()

If DR.HasRows = True Then
Dim vCID As New Collection()
While DR.Read()
vCID.Add(DR.Get Int32(0))
End While
Else
Return False
End If
End Using

--
Hope this helps
Jay B. Harlow [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"mg" <bi*****@gmail. comwrote in message
news:11******** **************@ 74g2000cwt.goog legroups.com...
| I'm migrating from VB6 and have a question about using 'Using' and the
| best way to use it.
|
| Here is a example of a small bit of code:
|
| dbConx("open")
| Using CN
| Dim CMD As New OleDbCommand(sS QL, CN)
| Dim DR As OleDbDataReader = CMD.ExecuteRead er()
|
| If DR.HasRows = True Then
| Dim vCID As New Collection()
| While DR.Read()
| vCID.Add(DR.Get Int32(0))
| End While
| DR.Close()
| CMD.Dispose()
| dbConx("close")
| Else
| DR.Close()
| CMD.Dispose()
| dbConx("close")
| Return False
| End If
| End Using
|
| dbConx creates an OleDbConnection CN and opens/closes it. The purpose
| of this is to return 0 or more record numbers for later use. If zero
| records are returned I just exit the function with a return of false.
| If records found, gather them into a collection and carry on, closing
| all resources used.
|
| In VB6 I used "set x=nothing" to clean-up.
|
| -What gets cleaned up within a 'Using' block?
| -Does my CMD and DR objects get cleaned up along with CN (so not
| needing all the .close and .dispose lines?
| -Any cleaner way to do this?
|
| Thanks!
|
Sep 1 '06 #9
mg
Jay thanks, you are a star! I don't mind the back-and-forth between
the alpha-devs, but was really looking for the practical, not the
theory, and you came through.

For me, my recent jump to .net from VB6 has moved me way out of my
comfort zone. I just have to get used to not being so productive for a
while...

Thanks again!
mg

Sep 1 '06 #10

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

Similar topics

3
1402
by: Tony Johansson | last post by:
Hello experts!! I reading in a book about C++ and there is something that I'm not sure about. I don't belive that the book is wrong but I will just ask you out there what you think. The book says the following "Note that you cannot assume that all resources are automatically released when the entire program tetminates. While this is true for resources allocated exclusively for
62
9210
by: ROSY | last post by:
hello experts plz answer following questions::: thanks in advance. 1. Out of fgets() and gets() which function is safe to use and why? 2. What is a far pointer? where we use it? 3. What does the error 'Null Pointer Assignment' mean and what causes this error? 4. What is near, far and huge pointers? How many bytes are occupied by them? 5. How would you obtain segment and offset addresses from a far address of a memory location?
21
1517
by: Roland | last post by:
The following issue is puzzling me: There are 2 ways of writing the code below: .... Dim fnt as Font = New Font(...) DrawString(myText, fnt,...) fnt.dispose(). or DrawString(myText, New Font(...),...)
4
3336
by: phl | last post by:
hi, My question is: 1. To avoid possible memory leaks, when you use this pattern, after you have dealth with the unmanaged resources and before you take your object off the finalize queue, how are you sure that your managed object resources are completely freed up of resources it's might be using? In my case below I have a private bool variable. Are there any other managed resource that you might need to explicitly free up in
1
1511
by: scpedicini | last post by:
Let's say that I've built an assembly, called myapi.dll whose default resource messages are english. Then let's say I create a german satellite assembly for the assembly called myapi.de.resources.dll. However, let's say that I have a german client who is using both myapi.dll and myapi.de.resources.dll; however, they would like to override a single resource string from myapi.de.resources.dll. Is it possible for them to create a "satellite...
7
6446
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
14
1672
by: Rob Wilkerson | last post by:
Hey all - Not being a seasoned PHP developer, tonight I started playing with the use of the Singleton pattern to store configuration information. What I was surprised to find was that the instance - at least the one I'm creating - isn't really a singleton. With each request, the constructor is called. Isn't that very much *not* a singleton or am I misunderstanding or doing something wrong? I'm using a pretty simple case:
5
5899
by: jehugaleahsa | last post by:
Hello: What is the point of using a DataTable in ASP .NET? We are unsure how you can use them without 1) rebuilding them every postback, or 2) taking up precious memory. We are not sure how to store a DataTable in any other way outside of our servers. In doing so, we leave ourselves open to large memory requirements. Furthermore, most web pages do not really support multiple changes per transaction. In other words, when the user submits...
0
2744
by: xrxst32 | last post by:
Hello there, I have some doubts about the best practice for using COM automation, the Runtime Callable Wrapper (RCW) and Marshal.ReleaseComObject. So the question is/are: Do I need to release each COM object explicit by a call to Marshal.ReleaseComObject, does the RCW take care of that or does it leaks unmanaged resources?
0
9703
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,...
0
10609
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10302
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
9445
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...
1
7846
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7024
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5691
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
5879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4498
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

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.