473,748 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stopping all threads

Hi
I have written a VB .NET app, which uses several threads. I thought
that when the user closes the main window (when MainForm.closed event
occures, and I call application.exi t) all running threads must abort,
but to my great surprise, running threads do not stop when
application.exi t is called. So I (or the users) have to stop threads
using Ctrl-Alt-Del.

Is there a way to stop ALL threads with a single instruction, without
having to run Thread.abort on each single thread?

thnx in advance,
and sorry for grammatical errors.
Nov 20 '05 #1
4 16402
"MSDousti" <MS******@myrea lbox.com> schrieb
Hi
I have written a VB .NET app, which uses several threads. I
thought that when the user closes the main window (when
MainForm.closed event occures, and I call application.exi t) all
running threads must abort, but to my great surprise, running threads
do not stop when application.exi t is called.
An application ends as soon as _all_ threads in the application have ended.
The thread creating the main form is only one of them.
So I (or the users) have
to stop threads using Ctrl-Alt-Del.

Is there a way to stop ALL threads with a single instruction,
without having to run Thread.abort on each single thread?


End
Usually, you should *not* use the End statment! You'd better initiate the
controlled end of the threads by setting a flag checked within the thread,
or, if the latter is not possible, call the thread's abort method.
--
Armin

http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #2
There are two types of threads, Background threads and Foreground threads.

Foreground threads will only exit when they have finished or have been
aborted.
Background threads will exit as soon as the last foreground thread has
exited.

Usually, foreground threads are used to handle user interface stuff (and
thus keep the application alive while they are running). Background threads
are used to perform tasks that can be interrupted when the main application
exits.

When launching threads, use the IsBackground property to tell the thread
what type it is.

When all foreground threads exit, the CLR will abort each background thread,
so be prepared to catch "ThreadAbortedE xception" exceptions.

Hope this helps,

Trev.

"MSDousti" <MS******@myrea lbox.com> wrote in message
news:bf******** *************** ***@posting.goo gle.com...
Hi
I have written a VB .NET app, which uses several threads. I thought
that when the user closes the main window (when MainForm.closed event
occures, and I call application.exi t) all running threads must abort,
but to my great surprise, running threads do not stop when
application.exi t is called. So I (or the users) have to stop threads
using Ctrl-Alt-Del.

Is there a way to stop ALL threads with a single instruction, without
having to run Thread.abort on each single thread?

thnx in advance,
and sorry for grammatical errors.

Nov 20 '05 #3
On 2003-12-06, MSDousti <MS******@myrea lbox.com> wrote:
Hi
I have written a VB .NET app, which uses several threads. I thought
that when the user closes the main window (when MainForm.closed event
occures, and I call application.exi t) all running threads must abort,
but to my great surprise, running threads do not stop when
application.exi t is called. So I (or the users) have to stop threads
using Ctrl-Alt-Del.

Is there a way to stop ALL threads with a single instruction, without
having to run Thread.abort on each single thread?

thnx in advance,
and sorry for grammatical errors.


As Codemonkey said - foreground threads (which are the default type)
will not exit until they have been aborted or completed - and an
application will not exit until all foreground threads have exited.

It is possible to set the IsBackground property, so that the thread will
be a background thread. Background threads will abort as soon as the
last foreground thread has exited - in other words, they won't keep the
application alive....

Personally, I don't like the idea of having threads forcibly closed at
the end of the application - so I tend not to use Background threads. I
have taken several approaches to this problem myself - but my current
solution I'm working on for simple threads is to inherit a worker thread
class from a class that looks like this... (Sorry for the C# code - but
that's what I do - it should be fairly easy to convert this to VB.NET
though :)

using System;
using System.Threadin g;

namespace FireAnt.Threadi ng
{
public abstract class WorkerThreadBas e : IDisposable
{

private Thread worker;
private ManualResetEven t waitHandle;
private object terminateLock;
private bool terminate;

// make sure that derived classes call one of the
// defined constructors
private WorkerThreadBas e() {}

// various constructors
public WorkerThreadBas e(string name) : this(name, false, ApartmentState. MTA) {}
public WorkerThreadBas e(string name, bool autoStart) : this(name, autoStart, ApartmentState. MTA) {}
public WorkerThreadBas e(string name, ApartmentState apartmentState) : this(name, false, apartmentState) {}

// this is the bad boy!
public WorkerThreadBas e(string name, bool autoStart, ApartmentState apartmentState)
{
if (name != null && name.Length > 0 )
{
// create some internal objects
this.waitHandle = new ManualResetEven t(false);
this.terminateL ock = new object();

// create a new thread and set some initial defaults.
this.worker = new Thread(new ThreadStart(thi s.ThreadMethod) );

this.worker.Nam e = name;
this.worker.Apa rtmentState = apartmentState;
if (autoStart)
{
this.Start();
}
}
else
{
throw new ArgumentExcepti on("Name can not be null or empty", "name");
}
}

~WorkerThreadBa se()
{
this.Stop(true) ;
this.waitHandle .Close();
}

/// <summary>
/// Get/Set the value of the threads name
/// </summary>
public string Name
{
get
{
return worker.Name;
}
set
{
worker.Name = value;
}
}

public WaitHandle WaitHandle
{
get
{
return this.waitHandle ;
}
}

public virtual void Start()
{
this.worker.Sta rt();
}

public virtual void Stop(bool wait)
{
if (this.worker.Is Alive)
{
this.Terminate = true;

if (wait)
{
this.worker.Joi n();
}
}
}

protected bool Terminate
{
get
{
bool result = false;

// create a criticle section here...
Monitor.Enter(t his.terminateLo ck);
result = this.terminate;
Monitor.Exit(th is.terminateLoc k);

return result;
}
set
{
// create a criticle section here...
Monitor.Enter(t his.terminateLo ck);
this.terminate = value;
Monitor.Exit(th is.terminateLoc k);
}
}

private void ThreadMethod()
{
try
{
// call the work method...
this.Work();
}
catch
{
// TODO: RAISE AN EVENT?
}
finally
{
// signal that we are teminating...
this.waitHandle .Set();
}
}

protected abstract void Work();

#region IDisposable Members

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

#endregion
}
}

This is still a work in progress, so I haven't worked out all the
details yet. It is sort of a starting point for a simplfied threading
framework. That's the reason to force the name for the thread. I'm
planning a collection class that probably will inherit from
DictionaryBase that will make management of groups of threads a little
simpler :) I got the idea for the class from an article I read
a couple of weeks ago - unfortunately, I can't remember where.

Anway the idea is that you can then use it like this:

public class Worker : WorkerThreadBas e
{

// define a constructor
Worker(string name, bool autoStart) : base(name, autoStart)
{
}

// override the work method
public override void Work()
{
int i = 0;
while (!this.Terminat e)
{
Console.WriteLi ne("{0} - {1}", this.Name, i);
Thread.Sleep(10 0);
i++;
}
}

public static void Main()
{
// create and start the threads
Worker w1 = new Worker("John", true);
Worker w2 = new Worker("Mary", true);

// wait for a while
Console.ReadLin e();

// stop them async
w1.Stop(false);
w2.Stop(false);

// wait for all threads to complete
WaitHandle.Wait All(new WaitHandle[] {w1.WaitHandle, w2.WaitHandle}) ;

// dispose unmanaged resources.
w1.Dispose();
w2.Dispose();
}
}

Anyway, maybe this will give you a starting point for your own threading
framework.
--
Tom Shelton
MVP [Visual Basic]
Nov 20 '05 #4
Hi,
thank u very much.
I found ur answers very useful, and it was of greatest help to me.
good luck.
Nov 20 '05 #5

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

Similar topics

6
7057
by: Fabiano Sidler | last post by:
Hello Newsgroup! In my Python script, I use the 'thread' module (not 'threading') and 'signal' simultaneously. All spawned threads execute 'pcapObject.loop(-1, callback)', which does not return. The problem now is: When the script catch a signal (let's say: SIGHUP), only the main thread is affected. But I need also the subthreads to be ended, because the script reopen()s files on SIGHUP and would also re-create the threads.
7
1794
by: python | last post by:
I have a script that downloads some webpages.The problem is that, sometimes, after I download few pages the script hangs( stops). (But sometimes it finishes in an excellent way ( to the end) and download all the pages I want to) I think the script stops if the internet connection to the server (from where I download the pages) is rather poor. Is there a solution how to prevent the script from hanging before all pages are downloaded? ...
3
2075
by: karl | last post by:
I have a windows service that creates a monitor thread which in turn creates 4 worker threads. Each thread is based upon a derived class (HL7Listener) of the TcpListener class. When running this service on my workstation I have no problems whatsoever. I then deployed this to another server and cannot open any of the sockets. Troubleshooting this issue I've discovered that the 4 threads do successfully enter the HL7Listener constructor....
12
6079
by: VMI | last post by:
My Windows form has two buttons: "Start" and "Stop". How can I stop the form from doing whatever it is doing without closing the whole application? The "Stop" button would have to stop a process that's being run in another class, not from within the form. Thanks.
5
1301
by: JSheble | last post by:
I have a service that upon startup it creates two threads: this.Batch = new ServiceThread(); this.Batch.FileSpec = "2*.XML"; this.tBatch = new Thread(new ThreadStart(this.Batch.WatchDir)); this.tBatch.Start(); this.AsNeeded = new ServiceThread(); this.AsNeeded.FileSpec = "1*.XML"; this.tAsNeeded = new Thread(new ThreadStart(this.AsNeeded.WatchDir));
11
1871
by: Steve | last post by:
I'm having a problem with my Thread usage and I think the general design of how I'm working with them. My UI class calls a method in another class that does a lot of work. That "worker" class looks something like this(pseudo code): class WorkerClass { Thread _listenerThread; public WorkerClass() {
2
2300
by: amadeusz.jasak | last post by:
Hello, it is possible to stop all threads (application) from thread of application: App |-MainThread |-WebServer |-CmdListener # From this I want to stop App The sys.exit isn't working...
1
2667
by: mclaugb | last post by:
Here is a simple piece of thread code. When i add the print (or other) function into the run method--the thread fails to stop after 2 seconds which the join(2) should ensure. I have a function that I must have timeout and cannot figure a way to do this. Any help appreciated. Should compile on 2.4 Bryan
4
5717
by: =?iso-8859-1?B?S2VyZW0gR/xtcvxrY/w=?= | last post by:
Hi, i have a main thread an another worker thread. The main Thread creates another thread and waits for the threads signal to continue the main thread. Everything works inside a ModalDialog and everyting is secured by Invoke/BeginInvoke, and synchronisation primitves like WaitHandles, Evetns, Semaphores, etc... All works good and with no race conditions or locks. I have a System.Windows.Forms.Timer in the main
0
8984
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
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
9530
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
9363
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...
1
9312
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
9238
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
8237
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
6793
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
6073
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();...

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.