473,847 Members | 1,802 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread.Abort issue

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 before it actually stop the thread

Thanks.
Nov 16 '05 #1
7 3297
I seem to remember that abort only works when the thread is in
wait/sleep/join state (i.e. doing some kind of wait operation) Not sure if
..Net thread wrapper changes that model or not. That said, aborting is
rather prute force. From your description, a better approach may be to have
your thread loop check a sync'd bool (or other) for stopped state. I
normally setup an State enum like Running, Stopped, Paused, etc. and check
that at the top of my loop. Then you can clean up and exit nicely. If your
thread still does not stop after some period of time (ie. 5 sec, etc) then
abort it and join with wait. I am not clear on what condition would cause
the thread not to respond to both your stop signal and the thread abort, but
things do go bump in the night, so may need to abort and wait, abort and
wait for some max times. At some point, you just have to give up and exit
with fatal error as something must be really wrong at that point.

--
William Stacey, MVP

"Morris" <an*******@disc ussions.microso ft.com> wrote in message
news:F9******** *************** ***********@mic rosoft.com...
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 before it actually stop the thread.
Thanks.


Nov 16 '05 #2
> "Morris" <an*******@disc ussions.microso ft.com> wrote in message
news:F9******** *************** ***********@mic rosoft.com...
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 before it actually stop the thread.
"William Stacey [MVP]" <st***********@ mvps.org> wrote in message
news:eG******** ******@TK2MSFTN GP10.phx.gbl... I seem to remember that abort only works when the thread is in
wait/sleep/join state (i.e. doing some kind of wait operation) Not sure if

That is not true. Thread.Interrup t raises a ThreadInterrupt edException on
the thread if the thread is in a join, wait or sleep state. Thread.Abort
will raise a ThreadAbortedEx ception in all cases, except if the thread is
executing interop-code or unmanaged code in which case the exception will be
re-thrown as soon as the thread starts executing managed code again.
.Net thread wrapper changes that model or not. That said, aborting is
rather prute force. From your description, a better approach may be to have

Agreed. Currently, a ThreadAbortedEx ception will leave a finally block if
the thread is executing it at that time. That is not very nice. I've heard
rumours that this could change in future versions of .NET.
your thread loop check a sync'd bool (or other) for stopped state. I
normally setup an State enum like Running, Stopped, Paused, etc. and check
that at the top of my loop. Then you can clean up and exit nicely. If your

That is one way. If the OP waits a lot using WaitHandle.Wait One,
WaitHandle.Wait All or WaitHandle.Wait Any then I suggest using
Thread.Interrup t on the thread that needs to be shut down. If not then the
OP could always check a volatile bool but he should not forget that polling
isn't very cpu-friendly. So he should leave some time (read: iterations) in
between checks.
thread still does not stop after some period of time (ie. 5 sec, etc) then
abort it and join with wait. I am not clear on what condition would cause
the thread not to respond to both your stop signal and the thread abort, but things do go bump in the night, so may need to abort and wait, abort and
wait for some max times. At some point, you just have to give up and exit
with fatal error as something must be really wrong at that point.
William Stacey, MVP


The only time that a thread would not repond to an Abort call is when the
thread is executing interop code or unmanaged code, and that the interop
code or unmanaged code blocks indefinitely or does not respond to the
ThreadAbortExce ption.

Cheers,
---
Tom Tempelaere
Nov 16 '05 #3
That is one way. If the OP waits a lot using WaitHandle.Wait One,
WaitHandle.Wait All or WaitHandle.Wait Any then I suggest using
Thread.Interrup t on the thread that needs to be shut down. If not then the
OP could always check a volatile bool but he should not forget that polling isn't very cpu-friendly. So he should leave some time (read: iterations) in between checks.
Yes but that is not polling per se. That is checking status at the top of
the loop before a wait - and the loop needs to be done anyway. The var
should be checked again after an top wait completes or timesout (i.e.
waiting on an empty queue, etc.)
The only time that a thread would not repond to an Abort call is when the
thread is executing interop code or unmanaged code, and that the interop
code or unmanaged code blocks indefinitely or does not respond to the
ThreadAbortExce ption.


Thanks for the clarifications. Cheers,

--
William Stacey, MVP

Nov 16 '05 #4
"William Stacey [MVP]" <st***********@ mvps.org> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
That is one way. If the OP waits a lot using WaitHandle.Wait One,
WaitHandle.Wait All or WaitHandle.Wait Any then I suggest using
Thread.Interrup t on the thread that needs to be shut down. If not then the OP could always check a volatile bool but he should not forget that

polling
isn't very cpu-friendly. So he should leave some time (read: iterations)

in
between checks.


Yes but that is not polling per se. That is checking status at the top of
the loop before a wait - and the loop needs to be done anyway. The var
should be checked again after an top wait completes or timesout (i.e.
waiting on an empty queue, etc.)


Checking a variable is double work. When you call Thread.Interrup t and the
thread is sleeping, joining or waiting then an exception is thrown to
unblock it. The exception itself tells you that the thread should stop
executing.

The only problem with this pattern is generic catch handlers. It will catch
all ThreadInterrupt edException exceptions and your thread would not repond
in that case. So one should be cautious with generic catch-handlers vs
thread interruption.

This is not true for a ThreadAbortedEx ception exception; it will be rethrown
at the end of each catch-handler it is caught in. If you call
Thread.ResetAbo rt (static) when you catch the ThreadAbortedEx ception then
that exception will no longer be rethrown.
The only time that a thread would not repond to an Abort call is when the thread is executing interop code or unmanaged code, and that the interop
code or unmanaged code blocks indefinitely or does not respond to the
ThreadAbortExce ption.


Thanks for the clarifications. Cheers,
--
William Stacey, MVP


No probs.

Cheers,
---
Tom Tempelaere
Nov 16 '05 #5
> Checking a variable is double work. When you call Thread.Interrup t and the
thread is sleeping, joining or waiting then an exception is thrown to
unblock it. The exception itself tells you that the thread should stop
executing.


I see your points, but do not agree it is "double" the work. A simple "if"
test is about the fastest thing you can do. Very quick. You also may need
to check var for different values such as Stopped, Paused, etc. Exceptions
are expensive in terms of how long they take. I would not use exceptions to
handle normal processing like this. Exceptions should be used for things
that can not be handled normally. This pattern of checking a var is seen in
many server designs, however the contrary is not seen so much AFAICT. It is
interesting, however, and probably has value for certain designs.

--
William Stacey, MVP
Nov 16 '05 #6
Well, I'm glad my question entertained you, but I am still searching for a good solution here. :) Please

In my case, I cannot
1/ Cannot handle Interupt or Abort exception: b/c that basically "interrupts " the block of code that needs to be completed before anything else may happen. That's why I said I had a "protected" section of code need to be blocked out (uninterruptabl e). Unless I can get something like "Resume Next" as saying below

2/ Cannot polling too long for the next "ready" time: b/c this thread is spawned by a window service and is aborted when OnStop() is called by SCM. As you may know, OnStop won't give you much time to poll for when the thread can be aborted

Ideally, I am looking for either of this
1/ A way to NICELY return the SCM's OnStop call and keep the service running if the thread cannot be aborted. I can check thread's status to return approriately

2/ Set the block of code protected from thread's abort/interrupt or (like VB) Resume Next when the exception happens (and deal with it after the code is complete

Any ideas? Thanks a bunch.
Nov 16 '05 #7
Lets see the basic worker loop your using. Remove anything not needed for
our purposes here.

--
William Stacey, MVP

"Morris" <an*******@disc ussions.microso ft.com> wrote in message
news:20******** *************** ***********@mic rosoft.com...
Well, I'm glad my question entertained you, but I am still searching for a good solution here. :) Please!
In my case, I cannot:
1/ Cannot handle Interupt or Abort exception: b/c that basically "interrupts " the block of code that needs to be completed before anything
else may happen. That's why I said I had a "protected" section of code need
to be blocked out (uninterruptabl e). Unless I can get something like "Resume
Next" as saying below.
2/ Cannot polling too long for the next "ready" time: b/c this thread is spawned by a window service and is aborted when OnStop() is called by SCM.
As you may know, OnStop won't give you much time to poll for when the thread
can be aborted.
Ideally, I am looking for either of this:
1/ A way to NICELY return the SCM's OnStop call and keep the service running if the thread cannot be aborted. I can check thread's status to
return approriately.
2/ Set the block of code protected from thread's abort/interrupt or (like VB) Resume Next when the exception happens (and deal with it after the code
is complete.
Any ideas? Thanks a bunch.


Nov 16 '05 #8

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

Similar topics

14
5368
by: Daisy | last post by:
From this page: http://www.c-sharpcorner.com/2/mt_beginner1.asp Thread class's Abort method is called to kill a thread permanently. Make sure you call IsAlive before Abort. if ( thread.IsAlive ) { thread.Abort(); }
20
3040
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...
2
2502
by: Sgt. Sausage | last post by:
New to multi-threading (less than 24 hours at it <grin>) Anyway, it's all making sense, and working fairly well thus far, but I'm having a minor issue I'm not sure how to get around. I've got a form that uses SqlDataAdapter. It fires off a thread to fill a DataSet. Not a big deal, this works. I've also got a requirement that the Thread that's going off to do the work -- if it takes too long, it has to
18
5867
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
3553
by: Soren S. Jorgensen | last post by:
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...
3
6182
by: Raj Wall | last post by:
Hi, I have an application that uses a number of sub-threads. What is the best way to do some processing in each thread when the main application is shut down? Is the ThreadAbortException thrown automatically for each thread? Or is there some other event or exception automatically thrown that the thread can "grab" as it is shut down?
0
2484
by: =?Utf-8?B?aGVyYmVydA==?= | last post by:
I read from a serialport using a worker thread. Because the worker thread t does not loop often, I cannot wait to terminate the worker thread using a boolean in the While condition. So I have a StopReader() method that simply aborts the worker thread (is there a better way for the above situation?). The StopReader creates an ObjectDisposedException when calling t.Abort(). WHY? Public Sub StopReader()
5
5084
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");
18
10250
by: =?Utf-8?B?VGhlU2lsdmVySGFtbWVy?= | last post by:
Because C# has no native SSH class, I am using SharpSSH. Sometimes, for reasons I do not know, a Connect call will totally lock up the thread and never return. I am sure it has something to do with weirdness going on with the server I am talking to. Anyhow, this locked up state happens once in a while (maybe once per day) and I can't figure out how to deal with the locked up thread. If I issue a Thread.Abort() the exception never...
0
9886
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
9730
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
10647
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
10706
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
10338
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
9482
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
7882
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
7056
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
5719
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...

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.