473,408 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Accessing private data during finalize/dispose

TB
I understand the basics of finalization and implementing IDisposable and how one is guaranteed access to managed objects only when working through the IDisposable interface.

My question is to what extent can I rely on access to my private data during the finalization process when *not* coming through the IDisposable interface? Are private members still valid or are they managed objects that may already be gone? Are some types accessible (int, char, double) but others not (string)?

Here is my dilemma... class A provides management for the creation and use of objects of class B, including marking these objects as "in use" (and unmarking them) out in the external world. Each B object instantiated keeps a reference to the A object used to create it. Class B implements the IDisposable interface and I want to ensure that the external "in use" flag for a B object is properly cleaned up no matter how the B object is being disposed of. Here is some pseudocode:

class A
{
public B CreateB(int ID)
{
if (MarkInUse(ID))
return new B(this, ID);
else
return null;
}

public bool MarkInUse(int ID) { ... }

public void MarkNotInUse(int ID) { ... }
}

class B : IDisposable
{
private A m_Manager;
private int m_ID;

public B(A manager, int ID)
{
m_Manager = manager;
m_ID = ID;
}

~B() { Dispose(false); }

public Dispose()
{
Dispose(true);
GC.SupressFinalize();
}

protected Dispose(bool disposing)
{
if (disposing)
// Clean up managed resources here

// Now clean up external resources
m_Manager.MarkNotInUse(m_ID); // ??? Is this valid ???
}
}

Can I still refer to 'm_Manager' here? I know I can do so reliably in the "if (disposing)" conditional -- but I need to unmark the object even if the calling code forgets to call Dispose on my object! I could duplicate the code necessary to unmark the object but need to keep two strings and an int to be able to do it. I'm reasonably sure that 'int' private data is accessible during finalization, but how about strings?

Thanks!
-- TB
Nov 15 '05 #1
6 2139
Hi TB,
Are some types accessible (int, char, double) but others not (string)? All data members of value types (int, char, double, enums, structs ) are
accessible, but reference types (strings, arrays, declared as classes) are
not guaranteed.
Can I still refer to 'm_Manager' here? I know I can do so reliably in the

"if (disposing)" conditional -- but I need to unmark the object even if the
calling code forgets to call Dispose on my object! I could duplicate the
code necessary to unmark the object but need to keep two strings and an int
to be able to do it. I'm reasonably sure that 'int' private data is
accessible during finalization, but how about strings?

Since class A doesn't declare *finalizer* that means you won't use any
unmanaged resources from A then "Yes, you can access m_Manager safely".
Why? Because class-B objects have finalizers. When they become garbage they
will be moved to the freachable queue, which is considered as a *root*
all objects referenced from class-B objects are still alive. Finalizers will
be executed by a worker thread and after that class-B objects will be
eligable for GC. How you can see class-A will be collected not before
finalization of the last class-B object it has created.

--
HTH
B\rgds
100
Nov 15 '05 #2
TB

----- Stoitcho Goutsev (100) [C# MVP] wrote: -----

Hi TB,
Are some types accessible (int, char, double) but others not (string)? All data members of value types (int, char, double, enums, structs ) are
accessible, but reference types (strings, arrays, declared as classes) are
not guaranteed.

Ok, this is what I gathered from reading the documentation. But this seems to contradict what you say next...
Can I still refer to 'm_Manager' here? I know I can do so reliably in the

"if (disposing)" conditional -- but I need to unmark the object even if the
calling code forgets to call Dispose on my object! I could duplicate the
code necessary to unmark the object but need to keep two strings and an int
to be able to do it. I'm reasonably sure that 'int' private data is
accessible during finalization, but how about strings?

Since class A doesn't declare *finalizer* that means you won't use any
unmanaged resources from A then "Yes, you can access m_Manager safely".
Why? Because class-B objects have finalizers. When they become garbage they
will be moved to the freachable queue, which is considered as a *root*
all objects referenced from class-B objects are still alive. Finalizers will
be executed by a worker thread and after that class-B objects will be
eligable for GC. How you can see class-A will be collected not before
finalization of the last class-B object it has created.

Let me see if I have this right...

Because my class B declares a finalizer (the ~B( ) "destructor"), it will be placed on the finalizer queue when garbage collected and kept "live". Because it is still "live" in this queue, any reference the class B instance holds is still valid -- even if these are to reference types (strings, arrays, classes). [doesn't this contradict the statement above??]

However, if class A also declared a finalizer (a ~A( ) "destructor"), then I would be SOL because both A and B instances would be placed in the finalizer queue and, although both are "live" while in the queue, their order of finalization is indeterminate and I can't guarantee that the reference to the A object inside of B is still valid when B's finalizer is eventually called.

So..., in this type of pattern, where a subordinate class object maintains a reference to a supervising object and needs access to it during finalization it is critical that the supervising class *not* implement a finalizer!!

Have I got it right??
Thanks!
-- TB

Nov 15 '05 #3


--
B\rgds
100
"TB" <tb*********@kaxy.NOSPAM.com> wrote in message
news:33**********************************@microsof t.com...

----- Stoitcho Goutsev (100) [C# MVP] wrote: -----

Hi TB,
> Are some types accessible (int, char, double) but others not
(string)? All data members of value types (int, char, double, enums, structs ) are accessible, but reference types (strings, arrays, declared as classes) are not guaranteed.

Ok, this is what I gathered from reading the documentation. But this seems to contradict what you say next...

Yes, you are right. Sorry. That was my last post before the end of the day
;) My statement above is not correct. You have access to all members of the
class.
However, if class A also declared a finalizer (a ~A( ) "destructor"), then I would be SOL because both A and B instances would be placed in the
finalizer queue and, although both are "live" while in the queue, their
order of finalization is indeterminate and I can't guarantee that the
reference to the A object inside of B is still valid when B's finalizer is
eventually called.
So..., in this type of pattern, where a subordinate class object maintains

a reference to a supervising object and needs access to it during
finalization it is critical that the supervising class *not* implement a
finalizer!!

Yes, you got it. However, If class A declares finalizer that doesn't mean
class-A object is not alive. It is still alive, but it might be already
finalized. which means that all unmanaged resources might be already
released. So you don't have to use anything which might be affected by
finalization. My point is that finalizer doesn't destroy the object in the
managed heap. That's why is somehow misleading to call it *destructor*. Bare
in mind that it is good practice to use finalizers to release unmanaged
resources only. I believe it is not good idea nulling references for
example. You don't gain anything with that.
In your case: Yes it is safe to unregister class-B objects when the objects
are disposed by the GC.

B\rgds
100
Nov 15 '05 #4
TB

----- Stoitcho Goutsev (100) [C# MVP] wrote: ----
--
B\rgd
10
"TB" <tb*********@kaxy.NOSPAM.com> wrote in messag
news:33**********************************@microsof t.com..
----- Stoitcho Goutsev (100) [C# MVP] wrote: ----
Hi TB
Are some types accessible (int, char, double) but others no (string)
All data members of value types (int, char, double, enums, structs ar accessible, but reference types (strings, arrays, declared a classes) ar not guaranteed
Ok, this is what I gathered from reading the documentation. But thi
seems to contradict what you say next..

Yes, you are right. Sorry. That was my last post before the end of the da
;) My statement above is not correct. You have access to all members of th
class

No problem, thanks for clearing that up
However, if class A also declared a finalizer (a ~A( ) "destructor"), the

I would be SOL because both A and B instances would be placed in th
finalizer queue and, although both are "live" while in the queue, thei
order of finalization is indeterminate and I can't guarantee that th
reference to the A object inside of B is still valid when B's finalizer i
eventually called So..., in this type of pattern, where a subordinate class object maintain

a reference to a supervising object and needs access to it durin
finalization it is critical that the supervising class *not* implement
finalizer!

Yes, you got it. However, If class A declares finalizer that doesn't mea
class-A object is not alive. It is still alive, but it might be alread
finalized. which means that all unmanaged resources might be alread
released. So you don't have to use anything which might be affected b
finalization. My point is that finalizer doesn't destroy the object in th
managed heap. That's why is somehow misleading to call it *destructor*. Bar
in mind that it is good practice to use finalizers to release unmanage
resources only. I believe it is not good idea nulling references fo
example. You don't gain anything with that
In your case: Yes it is safe to unregister class-B objects when the object
are disposed by the GC

Excellent, thanks! Not only do I think that I understand this much more now, but I can do what I need to do in my application safely!!! :-

-- T
Nov 15 '05 #5
"TB" <tb*********@kaxy.NOSPAM.com> wrote in message news:<6F**********************************@microso ft.com>...
I understand the basics of finalization and implementing IDisposable and how one is guaranteed access to managed objects only when working through the IDisposable interface.

My question is to what extent can I rely on access to my private data during the finalization process when *not* coming through the IDisposable interface? Are private members still valid or are they managed objects that may already be gone? Are some types accessible (int, char, double) but others not (string)?
Here is my dilemma... class A provides management for the creation and use of objects of class B, including marking these objects as "in
use" (and unmarking them) out in the external world. Each B object
instantiated keeps a reference to the A object used to create it.
Class B implements the IDisposable interface and I want to ensure that
the external "in use" flag for a B object is properly cleaned up no
matter how the B object is being disposed of. Here is some
pseudocode:
class A
{
public B CreateB(int ID)
{
if (MarkInUse(ID))
return new B(this, ID);
else
return null;
}

public bool MarkInUse(int ID) { ... }

public void MarkNotInUse(int ID) { ... }
}

class B : IDisposable
{
private A m_Manager;
private int m_ID;

public B(A manager, int ID)
{
m_Manager = manager;
m_ID = ID;
}

~B() { Dispose(false); }

public Dispose()
{
Dispose(true);
GC.SupressFinalize();
}

protected Dispose(bool disposing)
{
if (disposing)
// Clean up managed resources here

// Now clean up external resources
m_Manager.MarkNotInUse(m_ID); // ??? Is this valid ???
}
}

Can I still refer to 'm_Manager' here? I know I can do so reliably

in the "if (disposing)" conditional -- but I need to unmark the object
even if the calling code forgets to call Dispose on my object! I
could duplicate the code necessary to unmark the object but need to
keep two strings and an int to be able to do it. I'm reasonably sure
that 'int' private data is accessible during finalization, but how
about strings?

You can safely access other objects from a finalizer, as long they are
in no way affected by another finalizer. This is because no longer
accessible objects are finalized in completely arbitrary order (which
is in stark contrast to C++ where the order of destruction is
defined).

Therefore, your example works as long as class A does not have a
finalizer which modifies members that are directly or indirectly
accessed from ~B() (through MarkNotInUse). Moreover, none of A's
fields (or any of their fields) must have a finalizer. Since primitive
types (int, float, ... ) and strings do not define finalizers,
everything should work.

It wouldn't work if A contained e.g. a FileStream field that is
accessed from MarkNotInUse(), because FileStream defines a finalizer.

HTH,

Andreas
Nov 15 '05 #6
TB

----- Andreas Huber wrote: ----

[snip]

You can safely access other objects from a finalizer, as long they ar
in no way affected by another finalizer. This is because no longe
accessible objects are finalized in completely arbitrary order (whic
is in stark contrast to C++ where the order of destruction i
defined)

Therefore, your example works as long as class A does not have
finalizer which modifies members that are directly or indirectl
accessed from ~B() (through MarkNotInUse). Moreover, none of A'
fields (or any of their fields) must have a finalizer. Since primitiv
types (int, float, ... ) and strings do not define finalizers
everything should work

It wouldn't work if A contained e.g. a FileStream field that i
accessed from MarkNotInUse(), because FileStream defines a finalizer

HTH

Andrea

Yes, thanks Andreas (and Stoitcho)... It is intuitively satisfying, and most importantly..., it allows me do do what I need to do!! :-

-- T

Nov 15 '05 #7

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

Similar topics

2
by: Jack | last post by:
It seems that if Finalize takes more than 2 seconds during the process shutdown, the process will just terminate anyway. How can I specifically tells GC that this guy's clean up does suppose to...
2
by: Barry Anderberg | last post by:
I've been doing some reading about Finalize and garbage collection. I've learned that finalizing should be avoided because objects that have a finalize method require 2 (possibly more) itterations...
3
by: faktujaa | last post by:
Hi All, A small confusion. I have defined a connection class that has System.Data.IDbConnection as a member variable and implements IDisposable interface. I have implemented Dispose method to call...
2
by: damonf | last post by:
I'm currently trying to add an ASP hyperlink to a template column in a datagrid. The normal hyperlink column doesn't give me the ability to add attributes to the item. In my grid there are four...
20
by: Charles Law | last post by:
I have an application that creates a class. The class has unmanaged resources, so must end gracefully. How can I guarantee that the unmanaged resources are freed? I have looked at IDisposable,...
3
by: Boni | last post by:
Dear all, can somebody explain difference between Dispose and Finalize and when each of them should be used? Thank you very much, Boni
2
by: eBob.com | last post by:
I have a user control which creates an Excel spread sheet and badly needs Dispose/Finalize. I've read up on the subject in Balena and I think I understand what is going on. But the VS generated...
4
by: BLUE | last post by:
I've read many articles including the one from Duff's blog but I've many doubts. public static myClass Instance { get { if (myClass.instance == null) myClass.instance = new myClass();
8
by: Brian | last post by:
What's the best way to debug code that is being run during garbage collection? We are getting AccessViolationExceptions that seem to be happening during garbage collection. But when it hits the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
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...

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.