473,657 Members | 2,571 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

n00b question about destructors

I've got the following situation, simplified example of course. The
thread would be deep behind interfaces, classes, etc. Is there any way
to automagically exit it without having to add an Exit() call to
everywhere? I just want to break that loop when the application is
done (the thread is still running so it cannot be done, but I think
there is no more reference from the root object, so it could call the
destructor at least), or when the object containing this thread is
collected by the GC. Apparently, it never happens now.

class Program
{
static void Main(string[] args)
{
Program p = new Program();
}

private volatile bool _exit;

public Program()
{
_exit = false;

Thread _thread = new Thread(ThreadPr oc);

_thread.Start() ;
}

~Program()
{
_exit = true;
}

void ThreadProc()
{
while(!_exit)
{
Thread.Sleep(1) ;
}
}
}

Jun 19 '07 #1
9 1497
First of all, you can't use 'destructors' for this. Actually there are no
destrucktors in C# but finalizers. The originally were called destructors,
but they have very different semantics then destructors in e.g. C++.
Finalizers are called by the GC and can't be called deterministcall y.
Instead, you should use a method Abort or similar for this use.

You can call _thread.Abort() , wich will terminiate the thread. But that can
have very bad side effects, since the abortion can occur on any place in the
thread code. You're way (besides the wring use of finalizer) actually is the
recommended.

Christof
Jun 19 '07 #2
You can call _thread.Abort() , wich will terminiate the thread. But that can
have very bad side effects, since the abortion can occur on any place in the
thread code. You're way (besides the wring use of finalizer) actually is the
recommended.
I could even flip that _exit to true and then it would exit cleanly,
but this is running inside a class which is used through an interface
which doesn't have a call something like Shutdown().

On msdn I found the following. It suggests that at least in some cases
the destructor is called. I don't really care when, just once would be
great, to let the application exit :)

"The programmer has no control over when the destructor is called
because this is determined by the garbage collector. The garbage
collector checks for objects that are no longer being used by the
application. If it considers an object eligible for destruction, it
calls the destructor (if any) and reclaims the memory used to store
the object. Destructors are also called when the program exits."

Jun 19 '07 #3
On Jun 19, 4:18 pm, gab...@freemail .hu wrote:
You can call _thread.Abort() , wich will terminiate the thread. But that can
have very bad side effects, since the abortion can occur on any place in the
thread code. You're way (besides the wring use of finalizer) actually is the
recommended.

I could even flip that _exit to true and then it would exit cleanly,
but this is running inside a class which is used through an interface
which doesn't have a call something like Shutdown().

On msdn I found the following. It suggests that at least in some cases
the destructor is called. I don't really care when, just once would be
great, to let the application exit :)
[snip]

Do you actually need to have the thread self-terminate and run clean-
up, or are you just trying to make sure your application is able to
exit regardless of whether the thread is still running? If it's the
latter, set the IsBackground property of the thread to ensure it
doesn't prevent the process from terminating.
Matt

Jun 19 '07 #4
<ga****@freemai l.huschrieb
>
"The programmer has no control over when the destructor is called
because this is determined by the garbage collector. The garbage
collector checks for objects that are no longer being used by the
application. If it considers an object eligible for destruction, it
calls the destructor (if any) and reclaims the memory used to store
the object. Destructors are also called when the program exits."
This still wouldn't help in your case, because the object would'nt be
eligible for destruction/finalizaition before the thread ends. The thread
method is an instance method of the said object, and refers to the instance
field _exit. By this, it holds the object living.

Christof
Jun 19 '07 #5
Do you actually need to have the thread self-terminate and run clean-
up, or are you just trying to make sure your application is able to
exit regardless of whether the thread is still running? If it's the
latter, set the IsBackground property of the thread to ensure it
doesn't prevent the process from terminating.
In the end I solved it a different way, but I'll keep that in mind,
with IsBackground the process quits in the example. What I was really
trying to do was a scheduler thread to signal events at queued times.
Accuracy is another question, I found nothing better than calling
winmm.dll's time functions for 1ms precision.

Jun 20 '07 #6
This still wouldn't help in your case, because the object would'nt be
eligible for destruction/finalizaition before the thread ends. The thread
method is an instance method of the said object, and refers to the instance
field _exit. By this, it holds the object living.
Hmmm, but that object is not referenced by anything anymore. I thought
having a root object was the reason circular references can be cleaned
up in .net. The object which references the the _exit field and
spawned the thread was released at the end of the Main function, I
fail to see why the destructor cannot be called then.

Jun 20 '07 #7
lol, I just put a breakpoint inside the desctructor with IsBackground
= true and it stopped there. So, there is a clean way to release this
object afterall. (?)

Jun 20 '07 #8
On Jun 20, 7:07 pm, gab...@freemail .hu wrote:
lol, I just put a breakpoint inside the desctructor with IsBackground
= true and it stopped there. So, there is a clean way to release this
object afterall. (?)
Nope, the thread never wakes up while or after the destructor runs,
_exit = true has no effect.

Jun 20 '07 #9
<ga****@freemai l.huschrieb im Newsbeitrag
news:11******** **************@ n2g2000hse.goog legroups.com...
lol, I just put a breakpoint inside the desctructor with IsBackground
= true and it stopped there. So, there is a clean way to release this
object afterall. (?)
Yes, but because your working thread stopped before. Since you set
IsBackground = true (I suppose, this is on the working thread), the
application shuts down, when the main thread ends. Then the object becomes
eligible for destruction.
But if I understand your OP-code right, you wanted the destructor/finalizer
to stop the thread. That is not possible, if the thread references the
instance (and it does this by accessing _exit, wich actually is this._exit.)
So, the finalizer runs, but doesn't do what you expect.

Christof
Jun 21 '07 #10

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

Similar topics

3
21382
by: Rajesh Garg | last post by:
Can we have private constructors and destructors? IF yes what is the use of such constructors or destructors.....in the sense where can these be implemented in a system................. I have an idea that we can have private constructors and destructors but am not able to find a situation where they can be used... Regards RVG rajeshgarg@opussoft.com
12
1802
by: Ross Boylan | last post by:
I am trying to understand under what circumstances destructors get called with std::vector. I have an application in which I will put real objects, not just pointers, in the vector. 1. The standard says that empty() has constant complexity. If it actually called the destructor for each object, it seems to me it would have linear complexity. Does empty() call the destructor for each object in the container? If yes, why is it described...
8
1803
by: Edward Diener | last post by:
I have a __value class which uses some legacy C++ code. So I wrapped the legacy C++ code in another __nogc class and have a pointer to that class as a member of my __value class. When the __value class is created, I dynamically allocate an object of the class with the legacy C++ code. However because the __value class has no destructor, I can never release that allocated memory. Why does a __value class allow no destructor ? Without it I...
9
1249
by: Hasani \(remove nospam from address\) | last post by:
I was reading a ppt ( http://www.gotdotnet.com/team/pdc/4064/tls310.ppt ) and came aross this statement. "Users can leverage a destructor. The C++ compiler generates all the Dispose code automatically, including chaining calls to Dispose. (There is no Dispose pattern)" but Dispose can thrown an exception. Is the exception supressed?
5
1486
by: ElanKathir | last post by:
Hi All ! I want to know about the constructors & Destructors, constructors ---> New Destructors --> What ? (Which keyword to use for Destructor) Thanks & Regards, ElanKathir.S.N, ASM Technologies,
53
3160
by: jaso | last post by:
Can you give any comments on this code? I used one goto, is it bad? #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <assert.h> #define NOT_NULL 1
2
1470
by: ducky | last post by:
Hi all, The only programming experience i have under my belt so far is VB. I'm just starting out on C++ and wonder if anybody suggests and good (free) starting points for me to get going. I'm wondering about tutorials, source code, etc... Stuff that will take me from absolute square 1. Also, which compilers would be suggested? i have the bloodshed one and microsoft's visual studio express version as well. Are there any others that...
12
2868
by: Avalon1178 | last post by:
Hello, Are default destructors virtual? In other words, say I have "class A" and "class B : public A", and I have the code below: A * a = new A; B * b = new B; a = b;
6
5155
by: Jeff Newman | last post by:
Hello, Could anyone explain to me why the following class's destructor shows up as having multiple branches? (At least as judged by gcov 4.1.2 when compiled with gcc 4.1.2 ): struct blah { blah(); virtual ~blah();
0
8392
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
8823
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...
1
8503
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,...
0
8605
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
7321
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
6163
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
5632
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
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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.