473,322 Members | 1,431 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

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.exit) all running threads must abort,
but to my great surprise, running threads do not stop when
application.exit 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 16275
"MSDousti" <MS******@myrealbox.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.exit) all
running threads must abort, but to my great surprise, running threads
do not stop when application.exit 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 "ThreadAbortedException" exceptions.

Hope this helps,

Trev.

"MSDousti" <MS******@myrealbox.com> wrote in message
news:bf**************************@posting.google.c om...
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.exit) all running threads must abort,
but to my great surprise, running threads do not stop when
application.exit 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******@myrealbox.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.exit) all running threads must abort,
but to my great surprise, running threads do not stop when
application.exit 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.Threading;

namespace FireAnt.Threading
{
public abstract class WorkerThreadBase : IDisposable
{

private Thread worker;
private ManualResetEvent waitHandle;
private object terminateLock;
private bool terminate;

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

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

// this is the bad boy!
public WorkerThreadBase(string name, bool autoStart, ApartmentState apartmentState)
{
if (name != null && name.Length > 0 )
{
// create some internal objects
this.waitHandle = new ManualResetEvent(false);
this.terminateLock = new object();

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

this.worker.Name = name;
this.worker.ApartmentState = apartmentState;
if (autoStart)
{
this.Start();
}
}
else
{
throw new ArgumentException("Name can not be null or empty", "name");
}
}

~WorkerThreadBase()
{
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.Start();
}

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

if (wait)
{
this.worker.Join();
}
}
}

protected bool Terminate
{
get
{
bool result = false;

// create a criticle section here...
Monitor.Enter(this.terminateLock);
result = this.terminate;
Monitor.Exit(this.terminateLock);

return result;
}
set
{
// create a criticle section here...
Monitor.Enter(this.terminateLock);
this.terminate = value;
Monitor.Exit(this.terminateLock);
}
}

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.SuppressFinalize(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 : WorkerThreadBase
{

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

// override the work method
public override void Work()
{
int i = 0;
while (!this.Terminate)
{
Console.WriteLine("{0} - {1}", this.Name, i);
Thread.Sleep(100);
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.ReadLine();

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

// wait for all threads to complete
WaitHandle.WaitAll(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
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....
7
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...
3
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...
12
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...
5
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));...
11
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...
2
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
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...
4
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.