473,581 Members | 2,785 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

not receiving a ThreadAbortExce ption after thread.abort()

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(Cance lEventArgs e) in my
main GUI program, and have it perform the following on the thread:

if (thread.ThreadS tate == ThreadState.Sus pended || thread.ThreadSt ate ==
ThreadState.Sus pendRequested)
{
thread.Resume() ;
this.shutdown = true;
}
thread.Abort();

In other words, if the thread is suspended or on the way to get suspended, I
have to resume it befrore shutting it down. I've been debugging this on and
off, and everything but the thread.Abort() line seems to work fine, the
thread is properly reactivated and the ThreadState changed to
ThreadState.Run ning, but then when I call thread.Abort(), the ThreadState is
changed to ThreadState.Abo rtRequested and then nothing happens. The program
finishes and hangs because the thread hasn't been properly aborted. I have
tried a while (thread.ThreadS tate == ThreadState.Abo rtRequested){} but the
infinite loop is never aborted and the ThreadState never changes which leads
me to believe that the event I'm waiting for is never thrown. Is there a way
to manually trigger that exception and make sure it gets delivered?

Stephan Steiner
Nov 15 '05 #1
4 7360
I would avoid aborting the thread entirely, and put a flag in your app that
the loop in your worker thread checks every time through that you set when
you want it to exit. This should do what you want without worrying about
aborting anything.

Chris

bool stop = false;
void MainThreadFunct ion {
while (!stop) {
//thread work
}
}

MainForm_Closin g(object sending, CancelEventArgs e) {
stop = true;
//other stuff
}

"Stephan Steiner" <st*****@isuiss e.com> wrote in message
news:uz******** ******@TK2MSFTN GP09.phx.gbl...
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(Cance lEventArgs e) in my main GUI program, and have it perform the following on the thread:

if (thread.ThreadS tate == ThreadState.Sus pended || thread.ThreadSt ate ==
ThreadState.Sus pendRequested)
{
thread.Resume() ;
this.shutdown = true;
}
thread.Abort();

In other words, if the thread is suspended or on the way to get suspended, I have to resume it befrore shutting it down. I've been debugging this on and off, and everything but the thread.Abort() line seems to work fine, the
thread is properly reactivated and the ThreadState changed to
ThreadState.Run ning, but then when I call thread.Abort(), the ThreadState is changed to ThreadState.Abo rtRequested and then nothing happens. The program finishes and hangs because the thread hasn't been properly aborted. I have
tried a while (thread.ThreadS tate == ThreadState.Abo rtRequested){} but the
infinite loop is never aborted and the ThreadState never changes which leads me to believe that the event I'm waiting for is never thrown. Is there a way to manually trigger that exception and make sure it gets delivered?

Stephan Steiner

Nov 15 '05 #2

"Stephan Steiner" <st*****@shockf ish.com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Dave
Aborts will only be delivered if the thread is running (as you are aware). It may be that you have a race condition, where one thread is trying to
schedule an abort to a thread while another thread may be trying to suspend
it. It may also be that if a thread is in SuspendRequeste d state when you try to deliver the abort, it may be that it never gets properly set to the run state even after you invoke Thread.Resume. You could add some

diagnostic
code to try to capture this.

I did that and found out that there was indeed a thread.suspend scheduled
when I try to abort the thread. I try to re-enable the thread if the state
is suspended, but if the ThreadState is running when I make that check,

and then the thread gets suspended in the next timeslice, it will not be
re-enabled for the abort to be delivered.
Sounds like a classic race condition. I'd restructure the code so that the
signals were synchronized using events.


If I want to schedule work for a thread, such as receive/send a packet, I prefer to use Events (ManualResetEve nt, AutoResetEvent, or some other
synchronization primitive), and have the thread block in a while-loop
waiting for the event to get signaled.


I've been looking into this, however, I came across another problem: I'm
receiving packets, using ReceiveFrom which is blocking. Thus, even if a

have a WaitHandle.Wait Any or a WaitOne on the abovementioned ResetEvents, that
line is never executed because the ReceiveFrom is just sitting there,
blocking the thread. So, somehow I need a way to abort the ReceiveFrom and
restart the thread loop once I have set my ResetEvents. Is there any such
mechanism?

Typically you can close the socket that the ReceiveFrom is waiting on. This
should cause it to return from the call with an error or an exception
indication (I haven't used the sockets classes yet so I don't know which
form it will take).

Using an event to synchronize shutdown notifications usually works well. If
you combine the events with closing the sockets the thread is blocked on it
should work. You can also take a look at Rich Blum's book on network
programming in C#. I started reading it but until I have a project where I
need to learn more about it'll probably stay on the shelf - there should be
some examples in there on how you can structure this code. What you are
doing is pretty standard, vanilla network programming.


Nov 15 '05 #3
Dave
Typically you can close the socket that the ReceiveFrom is waiting on.

This should cause it to return from the call with an error or an exception
indication (I haven't used the sockets classes yet so I don't know which
form it will take).


That might well be, but I've been thinking about the next level already -
the reason why I haven't used events so far: Basically my program does (or
should do;) the following: permanently listen on the socket and forward
packets to a processing method in the UI thread domain (the receiver thead
fires an event to do that). Then once packets start coming in, they will
contain an indicator when the next databurst is to be expected, and as soon
as the first packet containg that info is received, a timer is started which
will reactivate (atm resume) the receiver thread at the appropriate time. At
the same time, there's another timer that is triggered periodically while
the receiver is active and which decides whether the thread should stay
active or not (be suspended). The decision criteria is whether new packets
have been received for a certain period or not. As if this wasn't enough,
disabling the receiver can also be triggered from the processing methods in
the GUI thread domain. So if I were to remove thread.Suspend and Resume and
use a ResetEvent class, I might be able to abort the ReceiveFrom by closing
the socket, which is okay when shutting down the program, but if I am to use
ResetEvents and WaitHandles to decide whether the thread receives incoming
packets, or shuts down, I cannot simply disconnect the socket to get to the
next WaitOne call in the receiver thread, as setting up a socket takes a lot
of time and has some issues (a buffering issue when you start sending /
receiving large amounts of data immediately after setting up the socket..
I've discussed that with Rich Blum already and I ended up with a small
workaround consisting of doing one send/receive operations when creating the
class containing the socket, as afterwards data bursts are no longer a
problem). I've just verified this, thread.Interrup t doesn't help either,
since ReceiveFrom doesn't block the thread.

Stephan
Nov 15 '05 #4
Ths may simply be a case where I don't understand what you are trying to
accomplish. I still don't see why you need to suspend/resume the threads,
especially the one you call the receiver thread. In other words, what is the
basic problem you are trying to solve by suspending/disabling the thread? Is
this for buffer overrun control?


"Stephan Steiner" <st*****@shockf ish.com> wrote in message
news:el******** *****@tk2msftng p13.phx.gbl...
Dave
Typically you can close the socket that the ReceiveFrom is waiting on.

This
should cause it to return from the call with an error or an exception
indication (I haven't used the sockets classes yet so I don't know which
form it will take).


That might well be, but I've been thinking about the next level already -
the reason why I haven't used events so far: Basically my program does (or
should do;) the following: permanently listen on the socket and forward
packets to a processing method in the UI thread domain (the receiver thead
fires an event to do that). Then once packets start coming in, they will
contain an indicator when the next databurst is to be expected, and as

soon as the first packet containg that info is received, a timer is started which will reactivate (atm resume) the receiver thread at the appropriate time. At the same time, there's another timer that is triggered periodically while
the receiver is active and which decides whether the thread should stay
active or not (be suspended). The decision criteria is whether new packets
have been received for a certain period or not. As if this wasn't enough,
disabling the receiver can also be triggered from the processing methods in the GUI thread domain. So if I were to remove thread.Suspend and Resume and use a ResetEvent class, I might be able to abort the ReceiveFrom by closing the socket, which is okay when shutting down the program, but if I am to use ResetEvents and WaitHandles to decide whether the thread receives incoming
packets, or shuts down, I cannot simply disconnect the socket to get to the next WaitOne call in the receiver thread, as setting up a socket takes a lot of time and has some issues (a buffering issue when you start sending /
receiving large amounts of data immediately after setting up the socket..
I've discussed that with Rich Blum already and I ended up with a small
workaround consisting of doing one send/receive operations when creating the class containing the socket, as afterwards data bursts are no longer a
problem). I've just verified this, thread.Interrup t doesn't help either,
since ReceiveFrom doesn't block the thread.

Stephan

Nov 15 '05 #5

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

Similar topics

3
2620
by: Anushya | last post by:
Hi When i abort a thread i get threadabort exception and wot all the things that need to be done there? IS releasing all the objects that are created is necesssary before aborting?Or aborting alone is sufficient? Join ing the thread till it is killed is impossible in my scenario as the exception is routed to some other layer. In the layer...
0
1908
by: Mark Phillips | last post by:
Hello, I am having a problem in which a file can get stuck open when a thread that is attempting to write to it gets aborted (ThreadAbortedException occurs). The log file gets stuck open until the process is shut down (cannot delete file from Windows Explorer, for example). My test application stops execution with: An unhandled exception...
6
3605
by: Bonj | last post by:
Say if i have a function, void FuncStart() { try { FuncDoActions(); //<nextlineofcode> } catch(ThreadAbortException)
6
2847
by: Mitch | last post by:
My background thread is being terminated when my application exixts. However, it does not receive a ThreadAbortException so I am unable to cleanly diconnect from a remote object (which makes the remote object fail). The thread does get aborted, just no exception is raised. If I explicitly call the thread.Abort() method, the exception is...
4
2899
by: Vivek | last post by:
Hi, I have a question regarding ThreadAbortException. Why is the thread abort exception rethrown at the end of a catch clause? Why is ThreadAbortException's behavior designed to be this way? Thanks in advance -Vivek
4
1728
by: splap20 | last post by:
Every day a large chunk of XML is posted up to my app via http. The app interprets this XML and writes results to a SQLServer. Occasionally a ThreadAbortException is thrown during this process. Despite being caught, this exception propagates all the way up the call stack. I know this is by design and that I can use Thread.ResetAbort to stop...
6
7436
by: foolmelon | last post by:
If a childThread is in the middle of a catch block and handling an exception caught, the main thread calls childThread.Abort(). At that time a ThreadAbortException is thrown in the childThread. The question is: after the ThreadAbortException is thrown, does the childThread continue run the remaining code in the catch block?
3
3333
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, I am running a web service which sometimes throws exceptions. I have a lot of error trapping within the web service, but I have missed the current problem. I am working on the current issue, but there even when I get this fixed, there may be others I have not thought of. My immediate problem is that the web service seems to throw a...
1
2570
by: Morgan Cheng | last post by:
This question may look silly. We have a cluster of Frontend ASP.NET Web Service calls other cluster of other ASP.NET Web Services. There is a hardware F5 BigIP load balancer between these two clusters. The topology is like below. Frontend Server1 --\ /--Backend Server 1 \ ...
0
7876
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...
0
7804
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...
0
8156
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. ...
1
7910
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...
0
8180
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...
0
6563
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...
0
3809
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...
0
3832
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1409
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.