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

Thread.Abort() and finally block

Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?
Nov 15 '05 #1
16 10045
"Bill" <fo*******@hotmail.com> wrote in message news:bc**************************@posting.google.c om...

Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?


Do the experiment.
This is the best way to find answer to such kind of questions.
Write a simple piece of code the models the situation and see what it does.
I.e. have a thread that sleeps for, say, 10 seconds in the final block and
then prints some message. Then have main thread start it, wait 2 seconds
and abort it. See if the message gets printed.

Off the top of my head, without writing and running the above example,
I believe the answer is "no". I.e., "finally" block will not be completed.

Ivan
Nov 15 '05 #2
The finally block is guaranteed to be called. There are very few exceptions
to this rule. Thread aborts aren't one of them.
--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Ivan Krivyakov" <i.***@verizon.net> wrote in message
news:O0*************@tk2msftngp13.phx.gbl...
"Bill" <fo*******@hotmail.com> wrote in message news:bc**************************@posting.google.c om...

Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?


Do the experiment.
This is the best way to find answer to such kind of questions.
Write a simple piece of code the models the situation and see what it

does. I.e. have a thread that sleeps for, say, 10 seconds in the final block and
then prints some message. Then have main thread start it, wait 2 seconds
and abort it. See if the message gets printed.

Off the top of my head, without writing and running the above example,
I believe the answer is "no". I.e., "finally" block will not be completed.

Ivan

Nov 15 '05 #3
From the help file:

"Unexecuted finally blocks are executed before the thread is aborted; this
includes any finally block that is executing when the exception is thrown."

-Rob Teixeira [MVP]

"Bill" <fo*******@hotmail.com> wrote in message
news:bc**************************@posting.google.c om...
Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?

Nov 15 '05 #4
That may be true for Longhorn but for the shipping version the finally block
will be interrupted.

Pls post the link to the help file so we can evaluate it.

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
From the help file:

"Unexecuted finally blocks are executed before the thread is aborted; this
includes any finally block that is executing when the exception is thrown."
-Rob Teixeira [MVP]

"Bill" <fo*******@hotmail.com> wrote in message
news:bc**************************@posting.google.c om...
Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?


Nov 15 '05 #5
If you are referring to code in a try block that is correct. However, the OP
asked what happens if the finally block itself is interrupted. The finally
block in v1.1. will be interrupted.

"Alvin Bruney" <vapor at steaming post office> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
The finally block is guaranteed to be called. There are very few exceptions to this rule. Thread aborts aren't one of them.
--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Ivan Krivyakov" <i.***@verizon.net> wrote in message
news:O0*************@tk2msftngp13.phx.gbl...
"Bill" <fo*******@hotmail.com> wrote in message

news:bc**************************@posting.google.c om...

Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?

Nov 15 '05 #6
The finally block can be interrupted.

There is one other little known way that finally blocks will not be
executed. If you have background threads (threadpool threads, manual
threads, etc.) running with finally blocks in them and you exit from the
last foreground thread in your app, the runtime will shutdown your
application (you can also force this yourself by calling Environment.Exit).
When this happens the runtime will suspend all threads except for the thread
it used to run finalizers. It never unwinds any of the threads in your app,
so no finally blocks at all will run. Object Finalizers still get called but
finally blocks never run.

"Bill" <fo*******@hotmail.com> wrote in message
news:bc**************************@posting.google.c om...
Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?

Nov 15 '05 #7
"Alvin Bruney" <vapor at steaming post office> wrote in message news:%2****************@TK2MSFTNGP10.phx.gbl...

The finally block is guaranteed to be called.
There are very few exceptions
to this rule. Thread aborts aren't one of them.


Finally block *is* called.
It is just not finished, since exception is thrown in the middle of it.

Do the experiment, as I suggested. Don't blindly believe the guarantees.

This program illustrates my point:

//-------------------------------------------------------------------------
using System;
using System.Threading;

namespace AbortThreadWhileInFinallyBlock
{
class Program
{
static int Indicator = 0;

static void MyThread()
{
try
{
Console.WriteLine("In try");
}
finally
{
Console.WriteLine("Start finally");
Thread.Sleep(10000);
Indicator = 1;
Console.WriteLine("End finally");
}

}

static void Main(string[] args)
{
Thread T = new Thread(new ThreadStart(MyThread));
T.Start();
Thread.Sleep(2000);
Console.WriteLine("Aborting the thread...");
T.Abort();
Console.WriteLine("Done aborting the thread. Indicator is {0}", Indicator);
}
}
}
//-------------------------------------------------------------------------

On my machine it prints this:

In try
Start finally
Aborting the thread...
Done aborting the thread. Indicator is 0

As you can see, "end finally" was not printed, and indicator value
was not set to one. The guarantee did not work.

Ivan
Nov 15 '05 #8
I completely expected the finally block to terminate cleanly. I've got the
same results as you by the way, which leads me to believe that it is
possible, theoretically at least, for the finally block to not be called if
a thread abort exception occurs immediately at the point of entry into a
finally block. At least that is what the code indicates, I don't believe the
literature supports this though. ???

--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Ivan Krivyakov" <i.***@verizon.net> wrote in message
news:uc**************@tk2msftngp13.phx.gbl...
"Alvin Bruney" <vapor at steaming post office> wrote in message news:%2****************@TK2MSFTNGP10.phx.gbl...

The finally block is guaranteed to be called.
There are very few exceptions
to this rule. Thread aborts aren't one of them.


Finally block *is* called.
It is just not finished, since exception is thrown in the middle of it.

Do the experiment, as I suggested. Don't blindly believe the guarantees.

This program illustrates my point:

//------------------------------------------------------------------------- using System;
using System.Threading;

namespace AbortThreadWhileInFinallyBlock
{
class Program
{
static int Indicator = 0;

static void MyThread()
{
try
{
Console.WriteLine("In try");
}
finally
{
Console.WriteLine("Start finally");
Thread.Sleep(10000);
Indicator = 1;
Console.WriteLine("End finally");
}

}

static void Main(string[] args)
{
Thread T = new Thread(new ThreadStart(MyThread));
T.Start();
Thread.Sleep(2000);
Console.WriteLine("Aborting the thread...");
T.Abort();
Console.WriteLine("Done aborting the thread. Indicator is {0}", Indicator); }
}
}
//-------------------------------------------------------------------------
On my machine it prints this:

In try
Start finally
Aborting the thread...
Done aborting the thread. Indicator is 0

As you can see, "end finally" was not printed, and indicator value
was not set to one. The guarantee did not work.

Ivan

Nov 15 '05 #9
<"Alvin Bruney" <vapor at steaming post office>> wrote:
I completely expected the finally block to terminate cleanly. I've got the
same results as you by the way, which leads me to believe that it is
possible, theoretically at least, for the finally block to not be called if
a thread abort exception occurs immediately at the point of entry into a
finally block. At least that is what the code indicates, I don't believe the
literature supports this though. ???


No - it's not that the finally block doesn't *start* executing - it's
that the thread is aborted while the finally block is *already*
executing. It's not like it's "at the point of entry" of the finally
block - it's slap bang in the middle.

Aborting threads is basically a bad idea, IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10
You misread what I said; we are in agreement.

When a ThreadAbortException is raised in a thread, then if the thread is
executing code in a try block the finally block will be executed. However,
if the code is already executing in the finally block the finally block will
be interrupted and will not complete.

Further, if you exit the process (e.g. with Environment.Exit or by allowing
the last foreground thread to exit) none of the finally blocks will execute.
All threads are suspended and are never resumed.

"Ivan Krivyakov" <i.***@verizon.net> wrote in message
news:uc**************@tk2msftngp13.phx.gbl...
"Alvin Bruney" <vapor at steaming post office> wrote in message news:%2****************@TK2MSFTNGP10.phx.gbl...

The finally block is guaranteed to be called.
There are very few exceptions
to this rule. Thread aborts aren't one of them.


Finally block *is* called.
It is just not finished, since exception is thrown in the middle of it.

Do the experiment, as I suggested. Don't blindly believe the guarantees.

This program illustrates my point:

//------------------------------------------------------------------------- using System;
using System.Threading;

namespace AbortThreadWhileInFinallyBlock
{
class Program
{
static int Indicator = 0;

static void MyThread()
{
try
{
Console.WriteLine("In try");
}
finally
{
Console.WriteLine("Start finally");
Thread.Sleep(10000);
Indicator = 1;
Console.WriteLine("End finally");
}

}

static void Main(string[] args)
{
Thread T = new Thread(new ThreadStart(MyThread));
T.Start();
Thread.Sleep(2000);
Console.WriteLine("Aborting the thread...");
T.Abort();
Console.WriteLine("Done aborting the thread. Indicator is {0}", Indicator); }
}
}
//-------------------------------------------------------------------------
On my machine it prints this:

In try
Start finally
Aborting the thread...
Done aborting the thread. Indicator is 0

As you can see, "end finally" was not printed, and indicator value
was not set to one. The guarantee did not work.

Ivan

Nov 15 '05 #11

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Alvin Bruney" <vapor at steaming post office>> wrote:
I completely expected the finally block to terminate cleanly. I've got the same results as you by the way, which leads me to believe that it is
possible, theoretically at least, for the finally block to not be called if a thread abort exception occurs immediately at the point of entry into a
finally block. At least that is what the code indicates, I don't believe the literature supports this though. ???


No - it's not that the finally block doesn't *start* executing - it's
that the thread is aborted while the finally block is *already*
executing. It's not like it's "at the point of entry" of the finally
block - it's slap bang in the middle.

Aborting threads is basically a bad idea, IMO.

It's supposed to be fixed in Longhorn, in which case finally blocks will no
longer be interrupted. It still doesn't address (so far as I know) what
happens when the application is exiting.
Nov 15 '05 #12
right,
but don't you see the problem though. you write a multithreaded app, where
you touch a database. In a finally construct, you free the resources. Guess
what happens before you get to the part where you free the resources. Boom,
a thread abort. Welcome to memory leak avenue, or gowd forbid you had a file
open and was hoping to close it. I can't be certain that the literature
indicates that a finally construct will execute to completion, I believe
that was probably inferred on my part based on the wording of the
literature.

Put another way, what is the point of a finally construct if it leads to
misbehavior? Should I just stay away from using abort? Not a bad price to
pay, BUT a thread can be aborted outside of your code as well. It's a
lose/lose situation.

Infact, depending on where your thread gets yanked off the stack, it could
never see the face of a finally construct. Consider:

[snip]
finally
//abort right here on entry
{
[snip]

the probability of this occuring increases as the complexity of a
multithreaded app grows.

--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Alvin Bruney" <vapor at steaming post office>> wrote:
I completely expected the finally block to terminate cleanly. I've got the same results as you by the way, which leads me to believe that it is
possible, theoretically at least, for the finally block to not be called if a thread abort exception occurs immediately at the point of entry into a
finally block. At least that is what the code indicates, I don't believe the literature supports this though. ???


No - it's not that the finally block doesn't *start* executing - it's
that the thread is aborted while the finally block is *already*
executing. It's not like it's "at the point of entry" of the finally
block - it's slap bang in the middle.

Aborting threads is basically a bad idea, IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #13
You are correct in that this is a lose/lose. That's why MSFT is correcting
this. There are other problems besides this, but this is a bad one.

In the meantime, if you have mission critical cleanup code one option is to
add a try-catch handler inside the finally block, so that if it catches a
ThreadAbortException you can retry the finally logic. It's ugly but it works
(I've tested it).

The best way to prevent a problem is to avoid it....don't throw any
ThreadAbortExceptions, and if unloading an AppDomain, use signaling between
your threads to know when they are at a safe point.

"Alvin Bruney" <vapor at steaming post office> wrote in message
news:eP**************@TK2MSFTNGP11.phx.gbl...
right,
but don't you see the problem though. you write a multithreaded app, where
you touch a database. In a finally construct, you free the resources. Guess what happens before you get to the part where you free the resources. Boom, a thread abort. Welcome to memory leak avenue, or gowd forbid you had a file open and was hoping to close it. I can't be certain that the literature
indicates that a finally construct will execute to completion, I believe
that was probably inferred on my part based on the wording of the
literature.

Put another way, what is the point of a finally construct if it leads to
misbehavior? Should I just stay away from using abort? Not a bad price to
pay, BUT a thread can be aborted outside of your code as well. It's a
lose/lose situation.

Infact, depending on where your thread gets yanked off the stack, it could
never see the face of a finally construct. Consider:

[snip]
finally
//abort right here on entry
{
[snip]

the probability of this occuring increases as the complexity of a
multithreaded app grows.

--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Alvin Bruney" <vapor at steaming post office>> wrote:
I completely expected the finally block to terminate cleanly. I've got the same results as you by the way, which leads me to believe that it is
possible, theoretically at least, for the finally block to not be called
if
a thread abort exception occurs immediately at the point of entry into
a finally block. At least that is what the code indicates, I don't
believe the literature supports this though. ???


No - it's not that the finally block doesn't *start* executing - it's
that the thread is aborted while the finally block is *already*
executing. It's not like it's "at the point of entry" of the finally
block - it's slap bang in the middle.

Aborting threads is basically a bad idea, IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Nov 15 '05 #14
It's amazing how much new stuff I learn everyday just by hanging around this
dump :-)

i meant that in a good way - dry humor
--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Dave" <no****************@wi.rr.com> wrote in message
news:OD****************@tk2msftngp13.phx.gbl...
You are correct in that this is a lose/lose. That's why MSFT is correcting
this. There are other problems besides this, but this is a bad one.

In the meantime, if you have mission critical cleanup code one option is to add a try-catch handler inside the finally block, so that if it catches a
ThreadAbortException you can retry the finally logic. It's ugly but it works (I've tested it).

The best way to prevent a problem is to avoid it....don't throw any
ThreadAbortExceptions, and if unloading an AppDomain, use signaling between your threads to know when they are at a safe point.

"Alvin Bruney" <vapor at steaming post office> wrote in message
news:eP**************@TK2MSFTNGP11.phx.gbl...
right,
but don't you see the problem though. you write a multithreaded app, where
you touch a database. In a finally construct, you free the resources. Guess
what happens before you get to the part where you free the resources.

Boom,
a thread abort. Welcome to memory leak avenue, or gowd forbid you had a

file
open and was hoping to close it. I can't be certain that the literature
indicates that a finally construct will execute to completion, I believe
that was probably inferred on my part based on the wording of the
literature.

Put another way, what is the point of a finally construct if it leads to
misbehavior? Should I just stay away from using abort? Not a bad price to pay, BUT a thread can be aborted outside of your code as well. It's a
lose/lose situation.

Infact, depending on where your thread gets yanked off the stack, it could never see the face of a finally construct. Consider:

[snip]
finally
//abort right here on entry
{
[snip]

the probability of this occuring increases as the complexity of a
multithreaded app grows.

--
Regards,
Alvin Bruney
Got DotNet? Get it here...
http://www.networkip.net/dotnet/tidbits/default.htm
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Alvin Bruney" <vapor at steaming post office>> wrote:
> I completely expected the finally block to terminate cleanly. I've
got the
> same results as you by the way, which leads me to believe that it is
> possible, theoretically at least, for the finally block to not be

called
if
> a thread abort exception occurs immediately at the point of entry

into a > finally block. At least that is what the code indicates, I don't

believe
the
> literature supports this though. ???

No - it's not that the finally block doesn't *start* executing - it's
that the thread is aborted while the finally block is *already*
executing. It's not like it's "at the point of entry" of the finally
block - it's slap bang in the middle.

Aborting threads is basically a bad idea, IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too



Nov 15 '05 #15
Dave,

No it' will (actually it is) be fixed in whidbey.

Willy.

"Dave" <no****************@wi.rr.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Alvin Bruney" <vapor at steaming post office>> wrote:
I completely expected the finally block to terminate cleanly. I've got the same results as you by the way, which leads me to believe that it is
possible, theoretically at least, for the finally block to not be called
if
a thread abort exception occurs immediately at the point of entry into
a finally block. At least that is what the code indicates, I don't
believe the literature supports this though. ???
No - it's not that the finally block doesn't *start* executing - it's
that the thread is aborted while the finally block is *already*
executing. It's not like it's "at the point of entry" of the finally
block - it's slap bang in the middle.

Aborting threads is basically a bad idea, IMO.

It's supposed to be fixed in Longhorn, in which case finally blocks will

no longer be interrupted. It still doesn't address (so far as I know) what
happens when the application is exiting.

Nov 15 '05 #16
Help files and real systems can act differently. A bug in the CLR aborts the
finalizer.
This will be (actually is) solved in the widbey realease
Willy.

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
From the help file:

"Unexecuted finally blocks are executed before the thread is aborted; this
includes any finally block that is executing when the exception is thrown."
-Rob Teixeira [MVP]

"Bill" <fo*******@hotmail.com> wrote in message
news:bc**************************@posting.google.c om...
Say I have a childThread currently is running a finally block to
cleanup external resources. At the same time the main thread calls
childThread.Abort(). The question is: when the ThreadAbortException
is thrown, does the childThread finish the remaining code in the
finally block?


Nov 15 '05 #17

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

Similar topics

2
by: cottonviking | last post by:
Greetings, all! I've been pondering the pitfalls of aborting a secondary thread in a service app I'm writing (VB, fx v1.1). Everything I've read so far pretty much dissuades one from aborting one...
14
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 (...
7
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...
20
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...
18
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...
4
by: fred | last post by:
I use a Synclock in a secondary thread and also stop the thread using the abort method. If the abort occurs while the thread is in the Synclock will the SyncLock always be released before the...
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. ...
6
by: mehdi | last post by:
Hi folks, You know, the Thread class has got a method named Abort which according to the msdn: "Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of...
20
by: =?ISO-8859-1?Q?Gerhard_H=E4ring?= | last post by:
John Dohn wrote: When I do this, I put a special value in the queue (like None) and in the worker thread, check for the special value and exit if found. Threads can also be marked as "daemon...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...

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.