473,661 Members | 2,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deterministic finalization -- how will clients of my stuff cope?

Hi folks.

So I'm in the middle of porting a large (previously COM-based) imaging
library to .Net. The clients of this library are VB programmers within the
company I work for. Their code will be getting ported to .Net at some point
in the near future too.

In the .Net world, many of my objects are forced to implement the
IDisposable+Fin alizer pattern because they hold onto unmanaged resources or
represent resources where deterministic release is an absolute requirement.
For example, image data lives in memory blocks allocated with VirtualAlloc.
Image files are read and written using Stream-derived classes.

I'm just kinda pondering how the need for IDisposable is going to impact the
other guys in the company. This basically adds a programming requirement
that did not exist before in the environment that these guys are used to
(VB6+COM). For example if the guy building VB-based image objects on top of
my classes forgets to call Dispose on my image objects at the right times,
several to several dozen MB of memory allocated with VirtualAlloc will
remain committed, and, since that memory is unmanaged, this will not help
trigger appropriately timed GCs. Yes, that memory will get cleaned up when
my object is finalized, but for interactive operations where many images
come and go in a short period of time, this is a killer.

What I am thinking is that it is going to be a continual battle to get these
guys to into the habit of calling Dispose and hopefully of using try/finally
(whatever the equivalent is in VB). Also, they will need to implement
IDisposable on any of their own classes that hold refs to my objects.

I think this is a disaster waiting to happen. VB guys are in general just
not used to this sort of programming model (please no flames, when I say "VB
programmers" I mean "the VB programmers at my company" -- who mostly have no
clue about system-level programming issues). They will resist dealing with
IDisposable and the right things just won't happen when their code is first
ported. "IDisposabl e-correctness" is a bit like "const-correctness" in
C++ -- since it tends to permeate and percolate upwards through the design,
it is a real pain to retrofit.

I am wondering if there is anything I can do to help with this problem. I
mean, it seems to me that the compiler and the CLR know when a reference is
being "released" -- why isn't there a mechanism whereby an object can
receive notifications that references have been added or removed to itself?
If I had that, I could consider implementing some kind of auto-Dispose. Sort
of like an "operator Referenced" and "operator Released" -- maybe this is
the same thing as trying to overload operator= (which can't be done in C#)?

class MyClass {

private int RefCount;

void op_Referenced()
{
RefCount++;
}

void op_Released()
{
if(--RefCount == 0) Dispose();
}
}

void somecode()
{
MyClass p = new MyClass(); // call p.op_Referenced
p = null; // call p.op_Released
}

Am I missing anything existing in VS .Net 2003 that might help me here?
Maybe VB.Net does this already and this isn't the issue I think it is gonna
be? Am I just nuts?
Nov 15 '05 #1
11 1398
Ted... Since no one has responded, here is my twisted code that will
crash the application on error! Remember, just because it can be done
does not mean it should be done!

class Debug
{
public static readonly bool isDebug= true;
}
/// <summary>
/// Summary description for Class1.
/// </summary>
///
class Class1
{
bool isDisposed= false;
~Class1()
{
if (!isDisposed)
{
if (Debug.isDebug) { throw new Exception();}
else {
System.Console. WriteLine("Log this.");
System.Console. ReadLine();
}
}
}
public bool MyDispose()
{
if (!isDisposed)
{
isDisposed= true;
return true;
}
else return false;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Class1 c= new Class1();
c.MyDispose();
c= null;
c= new Class1();
c= null;
}
}
Regards,
Jeff
What I am thinking is that it is going to be a continual battle to get

these guys to into the habit of calling Dispose<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #2
Well, that's an interesting approach, actually -- raise an exception or
crash or whatever if an object actually gets finalized, the idea being to
get someone's attention and tell them, hey! you forgot to finalize!
"Jeff Louie" <je********@yah oo.com> wrote in message
news:OD******** ******@TK2MSFTN GP11.phx.gbl...
Ted... Since no one has responded, here is my twisted code that will
crash the application on error! Remember, just because it can be done
does not mean it should be done!

class Debug
{
public static readonly bool isDebug= true;
}
/// <summary>
/// Summary description for Class1.
/// </summary>
///
class Class1
{
bool isDisposed= false;
~Class1()
{
if (!isDisposed)
{
if (Debug.isDebug) { throw new Exception();}
else {
System.Console. WriteLine("Log this.");
System.Console. ReadLine();
}
}
}
public bool MyDispose()
{
if (!isDisposed)
{
isDisposed= true;
return true;
}
else return false;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Class1 c= new Class1();
c.MyDispose();
c= null;
c= new Class1();
c= null;
}
}
Regards,
Jeff
What I am thinking is that it is going to be a continual battle to get

these guys to into the habit of calling Dispose<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #3
He He He. The devil made me write that code. I repent ;).

Regards,
Jeff
Well, that's an interesting approach, actually -- raise an exception or

crash or whatever if an object actually gets finalized, the idea being
to
get someone's attention and tell them, hey! you forgot to finalize!<
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #4
I was going to suggest the same thing - but maybe not throw the exception
but just log the offending class info. After all the exception will seem to
happen at random times and may be more confusing than writing to a log file.

The way I would set it up is:

1) Tell developers to check the log file. Some will, some won't.
2) Do code reviews prior to release (we always do this for all new code).
Not just for this issue - it's generally a great idea.
3) Tell QA to check the log file and reject a build if there are any entries
indicating IDisposable was not properly used

Eric

"Jeff Louie" <je********@yah oo.com> wrote in message
news:OD******** ******@TK2MSFTN GP11.phx.gbl...
Ted... Since no one has responded, here is my twisted code that will
crash the application on error! Remember, just because it can be done
does not mean it should be done!

class Debug
{
public static readonly bool isDebug= true;
}
/// <summary>
/// Summary description for Class1.
/// </summary>
///
class Class1
{
bool isDisposed= false;
~Class1()
{
if (!isDisposed)
{
if (Debug.isDebug) { throw new Exception();}
else {
System.Console. WriteLine("Log this.");
System.Console. ReadLine();
}
}
}
public bool MyDispose()
{
if (!isDisposed)
{
isDisposed= true;
return true;
}
else return false;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Class1 c= new Class1();
c.MyDispose();
c= null;
c= new Class1();
c= null;
}
}
Regards,
Jeff
What I am thinking is that it is going to be a continual battle to get

these guys to into the habit of calling Dispose<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


Nov 15 '05 #5
Well, I was playing around with this a little, and there's a StackTrace
class that can be wrapped inside a class that gets embedded in my objects to
hamdle this, including printing out a complete stack trace of where the
object that wasn't disposed was created. This is looking like a pretty good
idea.
"Eric Johannsen" <no*********@jo hannsen.us> wrote in message
news:z_******** **********@news svr25.news.prod igy.com...
I was going to suggest the same thing - but maybe not throw the exception
but just log the offending class info. After all the exception will seem to happen at random times and may be more confusing than writing to a log file.
The way I would set it up is:

1) Tell developers to check the log file. Some will, some won't.
2) Do code reviews prior to release (we always do this for all new code).
Not just for this issue - it's generally a great idea.
3) Tell QA to check the log file and reject a build if there are any entries indicating IDisposable was not properly used

Eric

"Jeff Louie" <je********@yah oo.com> wrote in message
news:OD******** ******@TK2MSFTN GP11.phx.gbl...
Ted... Since no one has responded, here is my twisted code that will
crash the application on error! Remember, just because it can be done
does not mean it should be done!

class Debug
{
public static readonly bool isDebug= true;
}
/// <summary>
/// Summary description for Class1.
/// </summary>
///
class Class1
{
bool isDisposed= false;
~Class1()
{
if (!isDisposed)
{
if (Debug.isDebug) { throw new Exception();}
else {
System.Console. WriteLine("Log this.");
System.Console. ReadLine();
}
}
}
public bool MyDispose()
{
if (!isDisposed)
{
isDisposed= true;
return true;
}
else return false;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Class1 c= new Class1();
c.MyDispose();
c= null;
c= new Class1();
c= null;
}
}
Regards,
Jeff
What I am thinking is that it is going to be a continual battle to get

these guys to into the habit of calling Dispose<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #6
FWIW, in debug mode, an unhandled exception is thrown and the
debugger takes you directly to the line of offending code. You can then
step over the exception.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #7
I think there's a lot of merit to this approach. The only change I would
make would be to think about adding a line to disable the exception when the
appdomain is unloading. Unless you can know that the Dispose should always
be called prior to the appdomain's termination you may get false exceptions.

~Class1()
{
if ( !AppDomain.Curr entDomain.IsFin alizingForUnloa d )
{
/// stuff goes here
}
}
"Ted Miller" <te*@nwlink.com > wrote in message
news:vr******** ****@corp.super news.com...
Well, that's an interesting approach, actually -- raise an exception or
crash or whatever if an object actually gets finalized, the idea being to
get someone's attention and tell them, hey! you forgot to finalize!

Nov 15 '05 #8
Thanks, and thanks to everyone else who took the time to post -- I think I
have some viable options now, to *force* the VB guys into learning how to do
the right thing.

--

"Dave" <no************ ****@wi.rr.com> wrote in message
news:uW******** *****@tk2msftng p13.phx.gbl...
I think there's a lot of merit to this approach. The only change I would
make would be to think about adding a line to disable the exception when the appdomain is unloading. Unless you can know that the Dispose should always
be called prior to the appdomain's termination you may get false exceptions.
~Class1()
{
if ( !AppDomain.Curr entDomain.IsFin alizingForUnloa d )
{
/// stuff goes here
}
}
"Ted Miller" <te*@nwlink.com > wrote in message
news:vr******** ****@corp.super news.com...
Well, that's an interesting approach, actually -- raise an exception or
crash or whatever if an object actually gets finalized, the idea being to get someone's attention and tell them, hey! you forgot to finalize!


Nov 15 '05 #9
I am putting this whole thing into practice. I created a
DisposableTrack edObject class that creates a StackTrace instance in its
constructor. My objects will embed these, i.e.,

class MyClass : IDisposable {
private DisposableTrack edClass m_Track = new DisposableTrack edClass();

Dispose() {
//...
m_Track.Dispose ();
//...
}
}

The finalizer for DisposableTrack edClass uses the stack trace it gathered
during construction to print out diagnostic info, etc (I am leaning towards
exceptions and logging). There is just one small glitch: the finalizer needs
to access the StackTrace, which is a non-static member variable. This is a
big no-no since it might have been collected already. To get around this, I
use GCHandle to hold an extra reference to the StackTrace object, thus
preventing it from being collected.

class DisposableTrack edObject : IDisposable
{
private StackTrace m_StackTrace;
private GCHandle m_StackTraceRef ;
private int m_Disposed;

public DisposableTrack edObject()
{
m_StackTrace = new StackTrace(0);
m_StackTraceRef = GCHandle.Alloc( m_StackTrace);
}

public void Dispose()
{
Dispose(true);
GC.SuppressFina lize(this);
}

~DisposableTrac kedObject()
{
Dispose(false);
}

private void Dispose(bool Disposing)
{
if(System.Threa ding.Interlocke d.CompareExchan ge(ref
m_Disposed,1,0) == 0) {
//
// Skip a frame to ignore this class.
//
if(st.FrameCoun t > 1) {
//
// The next frame up is the one where this object
was
// constructed -- which is the name of the class
that was not
// disposed.
//
string TrackedObjectNa me =
st.GetFrame(1). GetMethod().Dec laringType.Full Name;

//
// Write object name and stack trace.
//
Console.WriteLi ne("Object {0} not properly
disposed!",Trac kedObjectName);
if(st.FrameCoun t > 2) {
Console.WriteLi ne("Trace follows --");
for(int i=2; i<st.FrameCount ; i++) {
MethodBase m= st.GetFrame(i). GetMethod();

Console.WriteLi ne("{0}.{1}",m. DeclaringType.F ullName,m.Name) ;
}
}
Console.Out.Flu sh();
}
m_StackTrace = null;
m_StackTraceHan dle.Free();
}
}
}
"Dave" <no************ ****@wi.rr.com> wrote in message
news:uW******** *****@tk2msftng p13.phx.gbl...
I think there's a lot of merit to this approach. The only change I would
make would be to think about adding a line to disable the exception when the appdomain is unloading. Unless you can know that the Dispose should always
be called prior to the appdomain's termination you may get false exceptions.
~Class1()
{
if ( !AppDomain.Curr entDomain.IsFin alizingForUnloa d )
{
/// stuff goes here
}
}
"Ted Miller" <te*@nwlink.com > wrote in message
news:vr******** ****@corp.super news.com...
Well, that's an interesting approach, actually -- raise an exception or
crash or whatever if an object actually gets finalized, the idea being to get someone's attention and tell them, hey! you forgot to finalize!


Nov 15 '05 #10

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

Similar topics

2
2051
by: Rob Tweed | last post by:
I have a customer who is having problems when their Windows 2000/IIS/PHP-based system begins to experience a level of loading that isn't, in my view, unreasonably high. I'm wondering what others think, specifically: - are these volumes, for this kind of configuration, at or beyond the levels at which PHP should be able to cope? I hope not ! - what might be done to alleviate these problems? One of our suspicions is that Windows...
5
1432
by: rox.scott | last post by:
The following article says the .NET SOM will not allow what it calls "non-deterministic" schemas http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconnon-deterministicschema.asp ** Is this a bug in the SOM or in the schema ? ** Is it something that will be resolved in a future release? Actually, it is not my schema, but one that has been given to me by an international body, and validates on many...
2
1494
by: Frank Rizzo | last post by:
Ok, I need to get this straight in my head. When I implement a destructor in my class, is it guaranteed to be called when the class is destroyed or not? If not, when? Also, does the framework call .Dispose in my class and if so, does it call it when the class is destroyed. Or is it the responsibility of the parent class to call .Dispose. Thanks.
6
1008
by: Frank Rizzo | last post by:
Can someone give a reader's digest on finalization of objects in .net framework. When do I need to call .Dispose? What happens when I set the object to Nothing (or null in c#) What else do I need to know? Thanks
6
1925
by: Brian Gideon | last post by:
How have you handled the finalization of thread-specific unmanaged resources? My question pertains specifically to using the DDEML which is a thread-specific API. In other words, every call to the API using the same handle must be made on the same thread as the one that obtained the handle. Obviously, there is a conflict with the GC and the finalizer thread in cases where the programmer forgets to call Dispose on a wrapper class.
9
2996
by: plahey | last post by:
I have been dabbling in Python for a while now. One of the things that really appeals to me is that I can seem to be able to use C++-style RAII idioms to deal with resource management issues. For those that have no idea what I am talking about (I learn a lot reading posts on subjects in which I am clueless), consider the following code snippet: for line in file(name): ...print line,
32
2775
by: spibou | last post by:
Is the output of the C preprocessor deterministic ? What I mean by that is , given 2 compilers which conform to the same standard, will their preprocessors produce identical output given as input the same file ? If not then how much variation is allowed ? Is it just a bit more or less white space here and there or could could there be larger differences ? If the output is not deterministic then is it possible that the output of the...
4
1748
by: baramuse | last post by:
Hi all, before starting I must say that I'm a remoting beginner so I certainly didn't assimilate all the tricks of remoting so please be kind ;) Now here is my interrogation: I'm working on a client/server architecture for a callcenter software. The server is the only one connected to the oracle database and all the different clients (operator/admin...) are "connected" to the server via remoting (it's the best I've found to...
19
1468
by: abcd | last post by:
I am working on Vistual Studio since last 10 yrs. Working from VC++ 1.x and VB 3.x. Currently I am working in VS 6.0, classic ASP, COM, ADO. Today its called as old technologies. I have very novice++ expereince with .NET. Recently I appeared for one intvw and that guy just blasted me and FAILED me .. He asked CAS, threading, App domains, concurrency ADO.NET, and lots of advanced .NET questions even I have not encountered reading those. I...
0
8428
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8341
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
8754
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
8630
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
5650
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
4177
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
4343
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1984
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1740
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.