473,287 Members | 1,866 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,287 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 7341
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
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: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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...

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.