473,763 Members | 1,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(in t 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.SupressFinal ize();
}

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

// Now clean up external resources
m_Manager.MarkN otInUse(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 2159
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*********@ka xy.NOSPAM.com> wrote in message
news:33******** *************** ***********@mic rosoft.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*********@ka xy.NOSPAM.com> wrote in messag
news:33******** *************** ***********@mic rosoft.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*********@ka xy.NOSPAM.com> wrote in message news:<6F******* *************** ************@mi crosoft.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(in t 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.SupressFinal ize();
}

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

// Now clean up external resources
m_Manager.MarkN otInUse(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
1611
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 take that long so that please wait until I finish my job gracefully?
2
2100
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 of the garbage collector to run before the memory is returned to the heap. The first time the GC runs the Finalize method is called, then the second time the memory is actually freed. The problem is that most of the major classes in the .NET...
3
6074
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 Dispose method of IDbConnection. This Dispose method is called from a destructor. In the dispose method, i also call GC.SuppressFinalize(this) so as to avoid finalizer. All this was OK untill i came across one article that says - not to call...
2
2630
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 columns. Three are databound to a dataset and one is a template column. I need to be able to access each item in the template column (getting access to the hyperlink) then adding an attribute to call some client side code. Does anyone know...
20
7519
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, but this seems to rely on a call from the application, e.g. MyClass.Dispose()
3
1959
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
1296
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 coded confuses me a bit. VS generates a Dispose subroutine, but it's not obvious if it is ok to modify it. In the New subroutine VS makes clear that you can add code to it and tell you where to add it ("Add any initialization after the...
4
2033
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
2154
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 debugger, it is at whatever line of code the main thread was at when the garbage collector decided to run. In other words, the debugger is in irrelevant code. In general, if you have bugs in Dispose or finalization methods, what's the best...
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,...
0
10145
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9998
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
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
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
5406
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
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.