473,387 Members | 1,597 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,387 software developers and data experts.

not receiving a ThreadAbortException 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(CancelEventArgs e) in my
main GUI program, and have it perform the following on the thread:

if (thread.ThreadState == ThreadState.Suspended || thread.ThreadState ==
ThreadState.SuspendRequested)
{
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.Running, but then when I call thread.Abort(), the ThreadState is
changed to ThreadState.AbortRequested and then nothing happens. The program
finishes and hangs because the thread hasn't been properly aborted. I have
tried a while (thread.ThreadState == ThreadState.AbortRequested){} 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 7345
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 MainThreadFunction {
while (!stop) {
//thread work
}
}

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

"Stephan Steiner" <st*****@isuisse.com> wrote in message
news:uz**************@TK2MSFTNGP09.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(CancelEventArgs e) in my main GUI program, and have it perform the following on the thread:

if (thread.ThreadState == ThreadState.Suspended || thread.ThreadState ==
ThreadState.SuspendRequested)
{
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.Running, but then when I call thread.Abort(), the ThreadState is changed to ThreadState.AbortRequested and then nothing happens. The program finishes and hangs because the thread hasn't been properly aborted. I have
tried a while (thread.ThreadState == ThreadState.AbortRequested){} 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*****@shockfish.com> wrote in message
news:%2****************@tk2msftngp13.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 SuspendRequested 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 (ManualResetEvent, 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.WaitAny 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.Interrupt 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*****@shockfish.com> wrote in message
news:el*************@tk2msftngp13.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.Interrupt 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
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...
0
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...
6
by: Bonj | last post by:
Say if i have a function, void FuncStart() { try { FuncDoActions(); //<nextlineofcode> } catch(ThreadAbortException)
6
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...
4
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? ...
4
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....
6
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. ...
3
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,...
1
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...

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.