473,756 Members | 9,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

terminating all threads on program exit

Threads are not auto-terminated when the main form closes (not that
they should be). What's the best way to terminate them when the
program exits? Catch the on close message of the form, and give a
signal to the threads that they must shut down? Seems I need a
destructor for that. Forms don't have an overridable Dispose method.
So, how can I react when the form closes?

Note my example thread just (abnormally) runs forever until it is told
to shut down via boolean data member. So, the form's close method
could just set this. (I know there's the Abort() method, but that
seems ugly, especially since it's not guaranteed to work.)

Zytan

Mar 17 '07 #1
10 28766
Forms don't have an overridable Dispose method.
So, how can I react when the form closes?
FormClosed, FormClosing.

I wonder which is better? I doubt it matters in this case.

Zytan

Mar 17 '07 #2
Forms don't have an overridable Dispose method.
So, how can I react when the form closes?

FormClosed, FormClosing.

I wonder which is better? I doubt it matters in this case.
http://msdn2.microsoft.com/en-us/lib...rmclosing.aspx
"When a form is closed, it is disposed, releasing all resources
associated with the form. If you cancel this event, the form remains
opened."

I thought maybe you can cancel the close if you handle FormClosing.
But, if you are in FormClosed, everything it already disposed, meaning
it's probably too late to signal the threads to close. But, what's
the use of it, then? What could you possibly do in FormClosed if the
form is already disposed? The class data members must still exist,
thus meaning it's not too late to clean up stuff, like closing
threads.

Zytan

Mar 17 '07 #3
HI,
I have a same situation.
And my current solution is,
I encapsulate the thread in a class independently,a nd I have a Stop() public
method to terminal all the thread

//thread proc like this,where m_alive is a private datamember
private void ThreadProc()
{
while(m_alive)
{...}
}

//
public void Stop()
{
m_alive=false;
Thread.Sleep(10 00);
}

And in form1.Closing Event of the form which refrence the class,
if (threadClass.Al ive) threadClass.Sto p();

Also,I wonder this solution althrough is seems working well.

----------------------------------------------------------------------------------------
In my formerly project,I use WinApi with Delphi, The best solution is like
this,

//the procedure of thread
function ThreadProc(cons t p:Pointer):Card inal;stdcall;
begin
while WaitMessage do while PeekMessage(m,0 ,0,0,PM_REMOVE) do begin
case m.message of
WM_QUIT:Exit;
WM_OTHER_MSG:.. ..
end
end;

//when i want to terminal this thread ,just post a message to thread
PostThreadMessa ge(FThrID,WM_QU IT,0,0);
//where FThrId is the ID of the Thread

How and we do in c#?
How and we post a messge to a thread so that the threadproc can do a certain
thing ?

Waiting for Expert' Response.
Mar 17 '07 #4
gshzheng <gs******@gmail .comwrote:
HI,
I have a same situation.
And my current solution is,
I encapsulate the thread in a class independently,a nd I have a Stop() public
method to terminal all the thread

//thread proc like this,where m_alive is a private datamember
private void ThreadProc()
{
while(m_alive)
{...}
}

//
public void Stop()
{
m_alive=false;
Thread.Sleep(10 00);
}

And in form1.Closing Event of the form which refrence the class,
if (threadClass.Al ive) threadClass.Sto p();

Also,I wonder this solution althrough is seems working well.
Well, you need to be slightly careful - the above isn't guaranteed to
work unless m_alive is volatile.

See http://pobox.com/~skeet/csharp/threads/shutdown.shtml
----------------------------------------------------------------------------------------
In my formerly project,I use WinApi with Delphi, The best solution is like
this,

//the procedure of thread
function ThreadProc(cons t p:Pointer):Card inal;stdcall;
begin
while WaitMessage do while PeekMessage(m,0 ,0,0,PM_REMOVE) do begin
case m.message of
WM_QUIT:Exit;
WM_OTHER_MSG:.. ..
end
end;

//when i want to terminal this thread ,just post a message to thread
PostThreadMessa ge(FThrID,WM_QU IT,0,0);
//where FThrId is the ID of the Thread

How and we do in c#?
How and we post a messge to a thread so that the threadproc can do a certain
thing ?
You'll need to be running a message pump, and then use something like
Control.BeginIn voke.

However, I wouldn't recommend that solution. I don't see any reason to
bring in windows messages when there are more "pure .NET" ways of doing
it.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 17 '07 #5
Thanks,Jon,

Would you pls show me any "pure .NET" way to deal with thread?
I'm a newbie in this area.
Mar 17 '07 #6
gshzheng <gs******@gmail .comwrote:
Thanks,Jon,

Would you pls show me any "pure .NET" way to deal with thread?
I'm a newbie in this area.
Did you follow the link in my previous post?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 17 '07 #7
Sorry :)

I get it.
Thanks again.

"Jon Skeet [C# MVP]" <sk***@pobox.co m>
??????:MP****** *************** ***@msnews.micr osoft.com...
gshzheng <gs******@gmail .comwrote:
>Thanks,Jon,

Would you pls show me any "pure .NET" way to deal with thread?
I'm a newbie in this area.

Did you follow the link in my previous post?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Mar 17 '07 #8
Hi all!

I've got two observations:

The .NET forms do have overridable Dispose methods. The reason you
can't override them is because they are already overridden. The
override is in the <Form>.Designer .cs It's safe to modify this method,
the designer won't touch it.

If you use .NET2, the preferable way to create a background worker is
the component BackgroundWorke r. It provides you the functionality of
the abovementioned class, however, it is `official'. Also, the
component uses events to communicate with the form, so for example
when you report progress, you don't have to use any Invoke()-s,
because the worker.Progress Changed event runs in the form's thread.
See http://msdn2.microsoft.com/en-us/lib...undworker.aspx
for details.
(Sry, I don't know anything about .NET1)

BTW: the FormClosed is your way :)

Rgds

--
av

On Mar 17, 10:17 am, "gshzheng" <gshzh...@gmail .comwrote:
Sorry :)

I get it.
Thanks again.

"Jon Skeet [C# MVP]" <s...@pobox.com >
??????:MPG.2065 c0f3eb7dcb1098d ...@msnews.micr osoft.com...
gshzheng <gshzh...@gmail .comwrote:
Thanks,Jon,
Would you pls show me any "pure .NET" way to deal with thread?
I'm a newbie in this area.
Did you follow the link in my previous post?
--
Jon Skeet - <s...@pobox.com >
http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Mar 18 '07 #9
FormClosed, FormClosing.
>
I wonder which is better? I doubt it matters in this case.

http://msdn2.microsoft.com/en-us/lib....forms.form.fo...
"When a form is closed, it is disposed, releasing all resources
associated with the form. If you cancel this event, the form remains
opened."

I thought maybe you can cancel the close if you handle FormClosing.
But, if you are in FormClosed, everything it already disposed, meaning
it's probably too late to signal the threads to close. But, what's
the use of it, then? What could you possibly do in FormClosed if the
form is already disposed? The class data members must still exist,
thus meaning it's not too late to clean up stuff, like closing
threads.
Yup, either can be used. One is just 'better' in that you can stop
shut down if you want. The other, it's too late, you gotta clean up.
Like WM_CLOSE and WM_DESTROY, I believe.

Zytan

Mar 19 '07 #10

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

Similar topics

3
20129
by: DE | last post by:
Hello, I have an app with embedded Python. Python scripts create their own threads and I need to terminate these threads at the point where the user wants to leave the application. I use threading.Thread as base classes. I have tried to use call the join method of the python thread objects from C++. But although the call succeeds, the threads don't exit.
23
7590
by: Adam Clauss | last post by:
I have a C# Windows Service running as the NetworkService account because it needs to access a network share. As part of the service's initialization, I want the service to terminate, if an unrecoverable error occurs. When that case occurs, I create a ServiceController object and call the Stop() method. However - I get an exception thrown saying access denied. If I switch to using the LocalService account it works fine, but I lose...
19
11496
by: ern | last post by:
Right now I'm using exit(0) to terminate my program. My program is a console .exe application. After the "exit(0)" line of code is encountered, the console application waits for an enter press, before terminating. I want it to terminate completely without having to press enter manually. Anybody know what I might be missing here ?
3
2144
by: Martin Arvidsson | last post by:
Hi! I am starting up a thread that is listening for tcp connections in the thread i am using while (true) { // Handle the tcp stuff!! }
2
289
by: Matthew Tylee Atkinson | last post by:
I appear to be having some problems with the isAlive() method of detecting if a thread is alive/active/running or not. I'd be grateful for any advice. I have a visualisation program (which uses PyGame Extended ) that presents content to the user and is meant to download the next batch of content whilst the current one is being displayed. To achieve this, I created a thread to perform the downloading in the background (a class based on...
0
1229
by: Lloyd Zusman | last post by:
I have a python-2.5 program running under linux in which I spawn a number of threads. The main thread does nothing while these subsidiary threads are running, and after they all complete, the main thread will then exit. I know that I can manage this through the use of Thread.join(), but when I do it as follows, the main thread doesn't respond to signals: import sys, time, signal, threading
20
541
by: greg.johnsen80 | last post by:
I have been struggling with the following problem: In my console application I have function1 calling function2 which in turn uses threads to do computationally intensive tasks. Some of the threads generate exceptions which cause the whole application to abort. How can I avoid termination and make function1 call function2 again in case of exceptions. Any ideas would be highly appreciated.
4
2258
by: tdahsu | last post by:
All, I'd appreciate any help. I've got a list of files in a directory, and I'd like to iterate through that list and process each one. Rather than do that serially, I was thinking I should start five threads and process five files at a time. Is this a good idea? I picked the number five at random... I was thinking that I might check the number of processors and start a multiple of that, but then I remembered KISS and it seemed that...
7
3269
by: matthewaveryusa | last post by:
I have been reading a lot about aborting threads and there seems to be something missing to do this easily on program exit. This is what I want to do but I will need some help. I declared a global boolean called KillAllThreads (public static bool in abstact class). I initialize it to false in my main program before my main window opens. I then have some threads open and close. I keep count of opened and closed threads by using another...
0
9482
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
10062
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
9878
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
8733
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
7282
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
6551
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
5167
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...
2
3392
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2694
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.