473,787 Members | 2,924 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"forcing" garbage collection

I'm trying to wrap my ming around C#/CLR garbage collection. In an
ASP.NET project, I'm having a problem because an object destructor is
being called by another thread, long after my code is done. I'm wanting
to know if I can force it to happen immediately (when the object goes
out of scope) without going back and adding all of the required
Dispose() calls..

public Method()
{
CustomClass o = new CustomClass(..) ;
..
..
..
};

Is there a way to "force" the CustomClass destructor to be called right
when the object goes out of scope, by the same thread as the Method?

Thanks.
Jun 27 '08 #1
11 1742
On Mon, 26 May 2008 16:31:20 -0700, Jon Mcleod <jo***********@ yahoo.com>
wrote:
I'm trying to wrap my ming around C#/CLR garbage collection. In an
ASP.NET project, I'm having a problem because an object destructor is
being called by another thread, long after my code is done. I'm wanting
to know if I can force it to happen immediately (when the object goes
out of scope) without going back and adding all of the required
Dispose() calls..
There is a way.

But the right way to solve this issue is to call Dispose(). Either use
the "using" statement (preferable), or call Dispose() explicitly.

Don't fix buggy code by adding more bugs. If that means having to go back
and rewrite a bunch of code that wasn't dispoing of things properly, so be
it.

Pete
Jun 27 '08 #2
Jon Mcleod wrote:
I'm trying to wrap my ming around C#/CLR garbage collection. In an
ASP.NET project, I'm having a problem because an object destructor
destructor = finalizer ?
is
being called by another thread,
Some code explicit calling a finalizer ?
long after my code is done. I'm wanting
to know if I can force it to happen immediately (when the object goes
out of scope)
Making an explicit call ? Or an implicit call ? And what about the
reference in the other thread ?
without going back and adding all of the required
Dispose() calls..

public Method()
{
CustomClass o = new CustomClass(..) ;
..
..
..
};

Is there a way to "force" the CustomClass destructor to be called right
when the object goes out of scope, by the same thread as the Method?
Dispose is for unmanaged resources.

Garbage collection is for managed resources.

If the object only holds managed resources then let the GC do
what it wants to do when it want to do it.

If the object holds unmanaged resources then use the
Dispose pattern.

Arne

Jun 27 '08 #3
"Arne Vajhøj" <ar**@vajhoej.d kwrote in message
news:48******** *************** @news.sunsite.d k...
Jon Mcleod wrote:
>I'm trying to wrap my ming around C#/CLR garbage collection. In an
ASP.NET project, I'm having a problem because an object destructor

destructor = finalizer ?
> is
being called by another thread,

Some code explicit calling a finalizer ?
> long after my code is done. I'm wanting
to know if I can force it to happen immediately (when the object goes out
of scope)

Making an explicit call ? Or an implicit call ? And what about the
reference in the other thread ?
> without going back and adding all of the required
Dispose() calls..

public Method()
{
CustomClass o = new CustomClass(..) ;
..
..
..
};

Is there a way to "force" the CustomClass destructor to be called right
when the object goes out of scope, by the same thread as the Method?

Dispose is for unmanaged resources.

Garbage collection is for managed resources.

If the object only holds managed resources then let the GC do
what it wants to do when it want to do it.

If the object holds unmanaged resources then use the
Dispose pattern.

Arne
Dispose is also useful when the "managed" resource is actually an OS
resource such as a socket. In this case explicitly disposing the socket
frees up OS resources on two different machines.

Mike.
Jun 27 '08 #4
Michael D. Ober wrote:
"Arne Vajhøj" <ar**@vajhoej.d kwrote in message
news:48******** *************** @news.sunsite.d k...
>Jon Mcleod wrote:
>>I'm trying to wrap my ming around C#/CLR garbage collection. In an
ASP.NET project, I'm having a problem because an object destructor

destructor = finalizer ?
>> is
being called by another thread,

Some code explicit calling a finalizer ?
>> long after my code is done. I'm
wanting to know if I can force it to happen immediately (when the
object goes out of scope)

Making an explicit call ? Or an implicit call ? And what about the
reference in the other thread ?
>> without going back and adding all of the required
Dispose() calls..

public Method()
{
CustomClass o = new CustomClass(..) ;
..
..
..
};

Is there a way to "force" the CustomClass destructor to be called
right when the object goes out of scope, by the same thread as the
Method?

Dispose is for unmanaged resources.

Garbage collection is for managed resources.

If the object only holds managed resources then let the GC do
what it wants to do when it want to do it.

If the object holds unmanaged resources then use the
Dispose pattern.

Dispose is also useful when the "managed" resource is actually an OS
resource such as a socket. In this case explicitly disposing the socket
frees up OS resources on two different machines.
I would have assumed that sockets somewhere deep down contained
unmanaged resources.

Arne
Jun 27 '08 #5
On Mon, 26 May 2008 18:06:05 -0700, Michael D. Ober
<obermd.@.alum. mit.edu.nospam. wrote:
Dispose is also useful when the "managed" resource is actually an OS
resource such as a socket. In this case explicitly disposing the socket
frees up OS resources on two different machines.
As Arne says, the OS resource _is_ unmanaged. As for "on two different
machines", disposing your Socket instance locally does nothing one way or
the other with respect to freeing up a similar unmanaged resource on the
remote endpoint computer. That's up to the implementation on the other
end.

Pete
Jun 27 '08 #6
Michael D. Ober wrote:
>
Dispose is also useful when the "managed" resource is actually an OS
resource such as a socket. In this case explicitly disposing the socket
frees up OS resources on two different machines.
In this case, the object is a managed object but it contains a database
connection. This is an ASP.NET project, and there are two problems.
First, these objects are being left alive for quite some time, causing
the site to start artificially running out of database connections after
running a while. Secondly, GC happens on its own thread, causing a
"Internal .Net Framework Data Provider error 1." when it calls Close on
the the apparently single-threaded SqlConnection object.

My solution right now it to use IDisposed to explicitly manage the
lifetime of these objects, to sidestep the whole issue. I don't have a
lot of experience with these technologies, though. Is there a better way?
Jun 27 '08 #7
On May 27, 12:00 pm, Jon Mcleod <jonmcleod2...@ yahoo.comwrote:
Dispose is also useful when the "managed" resource is actually an OS
resource such as a socket. In this case explicitly disposing the socket
frees up OS resources on two different machines.

In this case, the object is a managed object but it contains a database
connection. This is an ASP.NET project, and there are two problems.
First, these objects are being left alive for quite some time, causing
the site to start artificially running out of database connections after
running a while. Secondly, GC happens on its own thread, causing a
"Internal .Net Framework Data Provider error 1." when it calls Close on
the the apparently single-threaded SqlConnection object.

My solution right now it to use IDisposed to explicitly manage the
lifetime of these objects, to sidestep the whole issue. I don't have a
lot of experience with these technologies, though. Is there a better way?
Disposing of the objects sounds like absolutely the right way to go.
However, in my experience it's almost always a bad idea to keep a
database connection alive in an object anyway. I find it's almost
always better to create the connection for the duration of the
database call, then close it. Connection pooling ensures efficiency of
physical connections, and you get away from a lot of the resource
issues it sounds like you're facing.

Jon
Jun 27 '08 #8
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Mon, 26 May 2008 18:06:05 -0700, Michael D. Ober
<obermd.@.alum. mit.edu.nospam. wrote:
>Dispose is also useful when the "managed" resource is actually an OS
resource such as a socket. In this case explicitly disposing the socket
frees up OS resources on two different machines.

As Arne says, the OS resource _is_ unmanaged. As for "on two different
machines", disposing your Socket instance locally does nothing one way or
the other with respect to freeing up a similar unmanaged resource on the
remote endpoint computer. That's up to the implementation on the other
end.

Pete

First, at some point every non-memory resource in dotNET is a OS resource
and closing it when done is a good thing to do. dotNET is very good at
reusing resources via pooling but Windows itself isn't, so using the dispose
pattern on just about any class that you use and/or create is a good idea
simply from the perspective of being nice to other applications on the
system. Second, most decent servers watch for and handle closed distant end
(client or server) sockets by closing a socket when a processing a zero byte
read. This is part of the Berkeley standard for socket communications.
Again, closing the non-memory resource via dispose is a good idea so that
any other systems involved in that resource are notified that they can close
their resources.

The real problem on whether or not to use dispose is that the framework has
blurred the lines between managed and unmanaged. For someone who has never
written to the underlying OS, the fact that a lot of the framework classes
contains a Dispose method really doesn't have any meaning because the
non-memory OS resource is "hidden" from them. Yes, if you don't explicitly
call obj.Dispose or use the "using" design pattern the framework will
eventually call Dispose and release the underlying resource, but this isn't
necessarily a good way of doing this.

Mike.
Jun 27 '08 #9
On Tue, 27 May 2008 16:40:51 -0700, Michael D. Ober
<obermd.@.alum. mit.edu.nospam. wrote:
First, at some point every non-memory resource in dotNET is a OS
resource and closing it when done is a good thing to do.
No one's suggested otherwise. Keep in mind, of course, that you are
confusing "close" with "dispose". It's true that many classes offer both,
and in many of those cases, the call to Close() does practically or
exactly the same thing as calling Dispose(). But they are two distinct
operations. It's a mistake to refer to one as if it's synonymous with the
other.
dotNET is very good at reusing resources via pooling but Windows itself
isn't,
..NET doesn't do any pooling, except in very specific, documented
scenarios. Even in the classes that implement pooling, you need to
release the resource being used so that it can be returned to the pool.
In at least one case, this involves calling Close() or Dispose() (in that
particular case, the two are equivalent).

I'm not really sure what point you're trying to make, but if you're saying
that one can rely on resource pooling from .NET as an alternative to
calling Close() or Dispose(), that's a very misleading and incorrect
implication to make.
so using the dispose pattern on just about any class that you use and/or
create is a good idea simply from the perspective of being nice to other
applications on the system.
In many cases, the application that is most critically affected by whether
you Close() or Dispose() a class is your own. It's not just a matter of
"being nice".
Second, most decent servers watch for and handle closed distant end
(client or server) sockets by closing a socket when a processing a zero
byte read. This is part of the Berkeley standard for socket
communications.
You are confusing the question of resource disposal and network API. The
socket comparison is apt for illustrating this, ironically enough. In BSD
terminology: a TCP socket uses shutdown() to initiate a graceful closure.
When you do this, the underlying TCP is eventually closed (including a
zero-byte receive at the other end), but the socket resource still lives
on. Not until you call closesocket() is the actual socket cleaned up, but
assuming a graceful closure, the remote endpoint has already been notified
of the closure of the connection (and may have itself already disposed its
own resources), even without disposal of the local resource.

(In .NET, this corresponds closely to the Socket.Shutdown () and
Socket.Close() methods).

Conversely, even if you reset a connection ungracefully (by calling
closesocket() without shutdown()), there is _nothing_ that guarantees that
the remote endpoint will even detect that correctly, never mind will clean
up its own resources. Resource management at the other end is _entirely_
up to the code running on that end.

It is a serious mistake to say that resource management within one's own
application is done for the sake of code running elsewhere. There are in
fact aspects of a network API (for example) that require considerate
behavior so that the other end can more effectively manage its own
resources, but these aspects are entirely independent of the question of
local resource management. Instead, they are part of the
application-level protocol that defines the interaction of the
applications, and this application-level protocol has nothing to do with
the underlying implementation.
Again, closing the non-memory resource via dispose is a good idea so
that any other systems involved in that resource are notified that they
can close their resources.
It's a good idea, but not for the reason you state.
The real problem on whether or not to use dispose is that the framework
has blurred the lines between managed and unmanaged. For someone who has
never written to the underlying OS, the fact that a lot of the framework
classes contains a Dispose method really doesn't have any meaning
because the non-memory OS resource is "hidden" from them.
If you are relying on whether a class implements IDisposable to tell you
whether it includes unmanaged resources, then yes...I can see your
confusion. But that's because IDisposable doesn't tell you that at all.
It's true that a class that includes unmanaged resources really needs to
implement IDisposable, but it's not necessarily the case that IDisposable
means there are unmanaged resources being used.

What you really should be taking away from the IDisposable issue is that
as a .NET programmer, you really shouldn't be worrying about whether some
other class uses unmanaged resources. If the class implements
IDisposable, you should call Dispose() when you're done with it, period.
Not because it might use unmanaged resources (though it very well might),
but because that's the contract defined by the class's API.

The "unmanaged/managed" question is really just a red herring. It's made
worse by your inaccurate claim that calling Dispose() is an effective and
correct way to manage an inter-process communication API (as in your
networking example).
Yes, if you don't explicitly call obj.Dispose or use the "using" design
pattern the framework will eventually call Dispose and release the
underlying resource, but this isn't necessarily a good way of doing this.
That's certainly true.

I'm sorry if it seems like I'm nitpicking, but IMHO it's very important to
get these details right. People synthesize new ideas from what they
believe they already know, and so even if from a practical sense, your
inaccuracies don't have any direct effect on a particular implementation,
feeding people bogus information can lead them to make unforeseen
erroneous decisions in the future. Anyone who treats IDisposable as part
of a protocol management strategy for inter-process communications is
eventually going to be write some code that doesn't do what they think it
does, introducing one or more bugs that are potentially difficult to find
and fix.

Pete
Jun 27 '08 #10

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

Similar topics

11
3644
by: Rohit | last post by:
Hi, Threads in the .NET Framework 1.1 (and possibly in 1.0 also) leak "Event" handles, by Event handles I mean Win32 Event handles which can be monitored using the ProcessExplorer from www.sysinternals.com, or even simply look at the Handle count in the good old windows TaskManager. To demonstrate the problem, all I did was created a basic Win Forms application and with Main implemented as:
4
1845
by: John Baker | last post by:
Hi: I have a query which supports a form. Te form is used to edit, update and change records in the table the query is based on. It all works fine EXCEPT that the "New" record (blank updatable record) always appears as the end of the form (i.e. the bottom), whereas it would be very helpful if it appeared at the beginning (the top of the form). Can anyone suggest a way to make this happen? Regards
46
2271
by: TTroy | last post by:
Hi, I'm just wondering why people/books/experts say "the function returns a pointer to.." or "we have to send scanf a pointer to.." instead of "the function returns the address of.." or "we have to send scanf the address of.." Isn't the lvalue called a POINTER TO and the (r)value called the ADDRESS OF?
2
3557
by: Earl Teigrob | last post by:
I have run into a situation where I need to run the !IsPostBack code under one circumstance, even if it is a postback. Something that may complicate matters more is that this is a double postback event. I have a filemanager type application that allows me to dynamically create a new folder on the web server. After the new folder is created, I need to reread the directory and display all the current folders in this directory to the user....
0
856
by: Mark | last post by:
At the top of my ASP.NET .aspx web page, I have several tags which I've included below. We store our ASP.NET projects in VSS. Every time I open up this project, VSS requires me to check out this page. Comparing the local file to the VSS copy, it keeps flipping the order of the register tags below. Any ideas on how to keep this from happening? Thanks in advance. -Mark <%@ Page language="c#" Codebehind="client_homepage.aspx.cs"...
51
3965
by: Tony Sinclair | last post by:
I'm just learning C#. I'm writing a program (using Visual C# 2005 on WinXP) to combine several files into one (HKSplit is a popular freeware program that does this, but it requires all input and output to be within one directory, and I want to be able to combine files from different directories into another directory of my choice). My program seems to work fine, but I'm wondering about this loop: for (int i = 0; i < numFiles; i++)
350
11896
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to days gone by?
7
2447
by: MLH | last post by:
If I drop Like "*ABC*" in a QBE grid criteria cell, the records returned include mixed case. Can I force the uppercase limitation in a QBE grid?
0
9497
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
10169
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...
1
10110
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,...
1
7517
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
6749
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
5398
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.