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

Home Posts Topics Members FAQ

Best/fastest way to abort worker thread

Hi,

In my app I've got a worker thread (background) doing some calculations
based upon user input. A new worker thread might be invoked before the
previous worker thread has ended, and I wan't only one worker thread running
at any time (if a new worker thread start has been requested, any running
worker thread results will be invalid). I'm using the below method to invoke
a new worker thread, but when stress testing this I'm sometimes getting a
System.Threadin g.ThreadStateEx ception (Thread is suspended; attempting to
abort) and everything locks up.

Does anyone now of a more fail safe method to successfully kill a ongoing
thread ??

private void StartWorker()
{
lock(this)
{
if(_calcThread != null)
{
while(_calcThre ad.IsAlive)
{
if(_calcThread. ThreadState !=
System.Threadin g.ThreadState.A bortRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspendRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspended)
{
_calcThread.Abo rt();
}
else
{
_calcThread.Joi n(50);
}
}

_calcThread = null;
}

_calcThread = new Thread(new ThreadStart(thi s.RunCalculatio n));
_calcThread.IsB ackground = true;
_calcThread.Pri ority = ThreadPriority. Highest;
_calcThread.Sta rt();
}

Thanks...

Soren

Feb 8 '06 #1
5 3537
Btw. it's in .NET 1.1 (2.0 is not an option pt.)

Soren
"Soren S. Jorgensen" <no****@nodomai n.com> skrev i en meddelelse
news:O%******** ********@TK2MSF TNGP15.phx.gbl. ..
Hi,

In my app I've got a worker thread (background) doing some calculations
based upon user input. A new worker thread might be invoked before the
previous worker thread has ended, and I wan't only one worker thread
running at any time (if a new worker thread start has been requested, any
running worker thread results will be invalid). I'm using the below method
to invoke a new worker thread, but when stress testing this I'm sometimes
getting a System.Threadin g.ThreadStateEx ception (Thread is suspended;
attempting to abort) and everything locks up.

Does anyone now of a more fail safe method to successfully kill a ongoing
thread ??

private void StartWorker()
{
lock(this)
{
if(_calcThread != null)
{
while(_calcThre ad.IsAlive)
{
if(_calcThread. ThreadState !=
System.Threadin g.ThreadState.A bortRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspendRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspended)
{
_calcThread.Abo rt();
}
else
{
_calcThread.Joi n(50);
}
}

_calcThread = null;
}

_calcThread = new Thread(new ThreadStart(thi s.RunCalculatio n));
_calcThread.IsB ackground = true;
_calcThread.Pri ority = ThreadPriority. Highest;
_calcThread.Sta rt();
}

Thanks...

Soren

Feb 8 '06 #2
Soren,

You shouldn't call Abort on threads for this purpose.

How you should terminate another thread is dependent on how you perform
processing in that thread.

If you are looping in the thread, performing your processing, then you
should check a shared variable (which has access to it synchronized, of
course) to see if the processing should stop. If you need to stop, then you
just exit the function when that variable indicates that the thread should
shut down.

If the processing is linear, then you will need to use a shared variable
as well, but you will have to decide at which points you check to see if
your processing should stop.

Now, you also want to know when the thread terminates. For this, you
could call Join on the thread (not in the thread itself, but on the instance
representing the worker thread) and wait for it to finish (of course, you
would only do this once you set your flag indicating that the thread should
stop).

However, I think that using Join is bad practice. Rather, you should
create an event, and signal the event in the worker thread when it is done.

Then, you can wait for the event to be signaled in the main thread, and
continue.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Soren S. Jorgensen" <no****@nodomai n.com> wrote in message
news:O%******** ********@TK2MSF TNGP15.phx.gbl. ..
Hi,

In my app I've got a worker thread (background) doing some calculations
based upon user input. A new worker thread might be invoked before the
previous worker thread has ended, and I wan't only one worker thread
running at any time (if a new worker thread start has been requested, any
running worker thread results will be invalid). I'm using the below method
to invoke a new worker thread, but when stress testing this I'm sometimes
getting a System.Threadin g.ThreadStateEx ception (Thread is suspended;
attempting to abort) and everything locks up.

Does anyone now of a more fail safe method to successfully kill a ongoing
thread ??

private void StartWorker()
{
lock(this)
{
if(_calcThread != null)
{
while(_calcThre ad.IsAlive)
{
if(_calcThread. ThreadState !=
System.Threadin g.ThreadState.A bortRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspendRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspended)
{
_calcThread.Abo rt();
}
else
{
_calcThread.Joi n(50);
}
}

_calcThread = null;
}

_calcThread = new Thread(new ThreadStart(thi s.RunCalculatio n));
_calcThread.IsB ackground = true;
_calcThread.Pri ority = ThreadPriority. Highest;
_calcThread.Sta rt();
}

Thanks...

Soren

Feb 8 '06 #3
Hi Nicolas,

Yes, I agree that previous posted example might not to be the best way to
end a worker thread, but the issue here is that the proccessing is actually
done in another module (and I'd really hate to begin changing this). So
there's really not a lot of points where it would be possible check if an
event is set signaling the worker thread to stop processing.
When prossecing is successfully done (or if another processing request has
not been submitted), the result is returned (from the worker) to main thread
through a delegate, in any other case it will/should be discarded. So the
only place where it would be suitable checking a signal would be just before
returning the result at the end of the thread. This will also do, but will
take up unnessecary resources on the client machine.

Soren

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> skrev i
en meddelelse news:uc******** ******@TK2MSFTN GP10.phx.gbl...
Soren,

You shouldn't call Abort on threads for this purpose.

How you should terminate another thread is dependent on how you perform
processing in that thread.

If you are looping in the thread, performing your processing, then you
should check a shared variable (which has access to it synchronized, of
course) to see if the processing should stop. If you need to stop, then
you just exit the function when that variable indicates that the thread
should shut down.

If the processing is linear, then you will need to use a shared
variable as well, but you will have to decide at which points you check to
see if your processing should stop.

Now, you also want to know when the thread terminates. For this, you
could call Join on the thread (not in the thread itself, but on the
instance representing the worker thread) and wait for it to finish (of
course, you would only do this once you set your flag indicating that the
thread should stop).

However, I think that using Join is bad practice. Rather, you should
create an event, and signal the event in the worker thread when it is
done.

Then, you can wait for the event to be signaled in the main thread, and
continue.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Soren S. Jorgensen" <no****@nodomai n.com> wrote in message
news:O%******** ********@TK2MSF TNGP15.phx.gbl. ..
Hi,

In my app I've got a worker thread (background) doing some calculations
based upon user input. A new worker thread might be invoked before the
previous worker thread has ended, and I wan't only one worker thread
running at any time (if a new worker thread start has been requested, any
running worker thread results will be invalid). I'm using the below
method to invoke a new worker thread, but when stress testing this I'm
sometimes getting a System.Threadin g.ThreadStateEx ception (Thread is
suspended; attempting to abort) and everything locks up.

Does anyone now of a more fail safe method to successfully kill a ongoing
thread ??

private void StartWorker()
{
lock(this)
{
if(_calcThread != null)
{
while(_calcThre ad.IsAlive)
{
if(_calcThread. ThreadState !=
System.Threadin g.ThreadState.A bortRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspendRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspended)
{
_calcThread.Abo rt();
}
else
{
_calcThread.Joi n(50);
}
}

_calcThread = null;
}

_calcThread = new Thread(new ThreadStart(thi s.RunCalculatio n));
_calcThread.IsB ackground = true;
_calcThread.Pri ority = ThreadPriority. Highest;
_calcThread.Sta rt();
}

Thanks...

Soren


Feb 8 '06 #4
Hi Nicolas,

Yes, I agree that previous posted example might not to be the best way to
end a worker thread, but the issue here is that the proccessing is actually
done in another module (and I'd really hate to begin changing this). So
there's really not a lot of points where it would be possible check if an
event is set signaling the worker thread to stop processing.
When prossecing is successfully done (or if another processing request has
not been submitted), the result is returned (from the worker) to main thread
through a delegate, in any other case it will/should be discarded. So the
only place where it would be suitable checking a signal would be just before
returning the result at the end of the thread. This will also do, but will
take up unnessecary resources on the client machine.

Soren

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> skrev i
en meddelelse news:uc******** ******@TK2MSFTN GP10.phx.gbl...
Soren,

You shouldn't call Abort on threads for this purpose.

How you should terminate another thread is dependent on how you perform
processing in that thread.

If you are looping in the thread, performing your processing, then you
should check a shared variable (which has access to it synchronized, of
course) to see if the processing should stop. If you need to stop, then
you just exit the function when that variable indicates that the thread
should shut down.

If the processing is linear, then you will need to use a shared
variable as well, but you will have to decide at which points you check to
see if your processing should stop.

Now, you also want to know when the thread terminates. For this, you
could call Join on the thread (not in the thread itself, but on the
instance representing the worker thread) and wait for it to finish (of
course, you would only do this once you set your flag indicating that the
thread should stop).

However, I think that using Join is bad practice. Rather, you should
create an event, and signal the event in the worker thread when it is
done.

Then, you can wait for the event to be signaled in the main thread, and
continue.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Soren S. Jorgensen" <no****@nodomai n.com> wrote in message
news:O%******** ********@TK2MSF TNGP15.phx.gbl. ..
Hi,

In my app I've got a worker thread (background) doing some calculations
based upon user input. A new worker thread might be invoked before the
previous worker thread has ended, and I wan't only one worker thread
running at any time (if a new worker thread start has been requested, any
running worker thread results will be invalid). I'm using the below
method to invoke a new worker thread, but when stress testing this I'm
sometimes getting a System.Threadin g.ThreadStateEx ception (Thread is
suspended; attempting to abort) and everything locks up.

Does anyone now of a more fail safe method to successfully kill a ongoing
thread ??

private void StartWorker()
{
lock(this)
{
if(_calcThread != null)
{
while(_calcThre ad.IsAlive)
{
if(_calcThread. ThreadState !=
System.Threadin g.ThreadState.A bortRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspendRequested &&
_calcThread.Thr eadState !=
System.Threadin g.ThreadState.S uspended)
{
_calcThread.Abo rt();
}
else
{
_calcThread.Joi n(50);
}
}

_calcThread = null;
}

_calcThread = new Thread(new ThreadStart(thi s.RunCalculatio n));
_calcThread.IsB ackground = true;
_calcThread.Pri ority = ThreadPriority. Highest;
_calcThread.Sta rt();
}

Thanks...

Soren


Feb 8 '06 #5
Use one worker thread and blocking queue. The worker blocks on empty queue.
When you post work to the queue the thread starts and does its thing. It
can post back to your UI using an event or calling a method on the form that
BeginInvokes a method on the UI thread.
Here is example using a blocking queue:
http://channel9.msdn.com/ShowPost.aspx?PostID=161030

--
William Stacey [MVP]

"Soren S. Jorgensen" <no****@nodomai n.com> wrote in message
news:O%******** ********@TK2MSF TNGP15.phx.gbl. ..
| Hi,
|
| In my app I've got a worker thread (background) doing some calculations
| based upon user input. A new worker thread might be invoked before the
| previous worker thread has ended, and I wan't only one worker thread
running
| at any time (if a new worker thread start has been requested, any running
| worker thread results will be invalid). I'm using the below method to
invoke
| a new worker thread, but when stress testing this I'm sometimes getting a
| System.Threadin g.ThreadStateEx ception (Thread is suspended; attempting to
| abort) and everything locks up.
|
| Does anyone now of a more fail safe method to successfully kill a ongoing
| thread ??
|
| private void StartWorker()
| {
| lock(this)
| {
| if(_calcThread != null)
| {
| while(_calcThre ad.IsAlive)
| {
| if(_calcThread. ThreadState !=
| System.Threadin g.ThreadState.A bortRequested &&
| _calcThread.Thr eadState !=
| System.Threadin g.ThreadState.S uspendRequested &&
| _calcThread.Thr eadState !=
| System.Threadin g.ThreadState.S uspended)
| {
| _calcThread.Abo rt();
| }
| else
| {
| _calcThread.Joi n(50);
| }
| }
|
| _calcThread = null;
| }
|
| _calcThread = new Thread(new ThreadStart(thi s.RunCalculatio n));
| _calcThread.IsB ackground = true;
| _calcThread.Pri ority = ThreadPriority. Highest;
| _calcThread.Sta rt();
| }
|
| Thanks...
|
| Soren
|
|
|
Feb 8 '06 #6

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

Similar topics

4
2250
by: Jeff | last post by:
I am running a worker thread that manipulates some hardware setting every so often. My problem is that the hardware manipulation cannot be interrupted once it has started How can I ensure that the entire operation will run to completion even when the ThreadAbortException is thrown Thanks Jeff
4
7367
by: Stephan Steiner | last post by:
Hi I'm having some weird threading issues.. almost at random, if I dare change a line of my code, the shutdown sequence gets messed up. I'm using a thread to receive data from the network, that I suspend and resume whenver needed. In order to properly shut down the program every thread has to be aborted. So, I override OnClosing(CancelEventArgs e) in my main GUI program, and have it perform the following on the thread: if...
7
3279
by: Morris | last post by:
I want to abort a running thread, so I call MyThread.abort() function. My problem is this thread runs "almost" like a while(true) loop and I don't want the Abort() function interrupts the thread at any point in the thread. In fact, I have a section of code needs to be "protected" from being interrupted. How can I make sure Abort() will not land anywhere winthin this block? In other words, the Abort() must wait until this block of code is done...
20
3011
by: Doug Thews | last post by:
I ran into an interesting re-pain delay after calling the Abort() method on a thread, but it only happens the very first time I call it. Every time afterward, there is no delay. I've got a delegate inside the UI that I call to update the progress meter. I use the Suspend() and Abort() methods based on button events. I can watch the progress meter increase just fine when the thread is running. When I select Start, I enable the Cancel...
6
10744
by: LP | last post by:
Hi, I am starting a new thread from the main UI thread. If users clicks cancel button, the thread is aborted: workerThread.Abort(); ThreadAbort Exception is handeled in the worker thread: catch (System.Threading.ThreadAbortException ex)
1
2053
by: Ennixo | last post by:
hi, i coded an application in which i can move a slider to define a radius and it computes a gaussian blur in a thread. because the Scroll event of the slider is often raised, i use one thread (declared in the form's class) that i abort when it is already existing and running. this works well but sometimes i've got this error (translated from
18
5846
by: Urs Vogel | last post by:
Hi I wrote an application server (a remoting sinlgeton), where processes must be stopped in very rare cases, done thru a Thread.Abort(). Occasionally, and only after a Thread.Abort(), this component becomes instabile, throwing a Windows like error (access violation on 0x00000002), not an framework exception. The component and all of its subcomponents are 100% managed code. What could go wrong with Thread.Abort()? Thanks for any hints.
5
5071
by: andrew | last post by:
Hi, I have the following issue with the Thread.Abort(): The main thread creates a worker thread which waits on a process termination. void ThreadProc() { Process proc = proc.Start("notepad.exe");
7
7676
by: Marc Bartsch | last post by:
Hi, I have a background worker in my C# app that makes a synchronous HttpWebRequest.GetResponse() call. The idea is to POST a file to a server on the internet. When I call HttpWebRequest.Abort() on the request object on another thread, GetResponse() returns with an exception as expected. However, when I monitor the network traffic, it does not seem to stop, but to continue to be active and to upload the file. The network is active even...
0
8326
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
8845
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
8622
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
7355
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...
0
5647
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
4173
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
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2745
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
2
1736
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.