Reputation: 3850
under both aborted and completed situations, ThreadState
will be Stopped
.
How to differentiate between them?
Upvotes: 0
Views: 6905
Reputation: 19881
Note how the ThreadState
enum is declared:
[FlagsAttribute]
public enum ThreadState { ... }
...Sinc it is a [Flag]
this means a thread can be in multiple states.
MSDN, ThreadState Enumeration (emphasis added by me):
ThreadState defines a set of all possible execution states for threads. Once a thread is created, it is in at least one of the states until it terminates. Threads created within the common language runtime are initially in the Unstarted state, while external threads that come into the runtime are already in the Running state. An Unstarted thread is transitioned into the Running state by calling Start. Not all combinations of ThreadState values are valid; for example, a thread cannot be in both the Aborted and Unstarted states.
...and then goes on to say:
A thread can be in more than one state at a given time. For example, if a thread is blocked on a call to Wait, and another thread calls Abort on the blocked thread, the blocked thread will be in both the WaitSleepJoin and the AbortRequested states at the same time. In this case, as soon as the thread returns from the call to Wait or is interrupted, it will receive the ThreadAbortException to begin aborting.
The Thread.ThreadState property of a thread provides the current state of a thread. Applications must use a bitmask to determine whether a thread is running. Since the value for Running is zero (0), test whether a thread is running by using C# code such as
(myThread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0
Upvotes: 1
Reputation: 27282
The only way I can think of is to set a "completed" flag as the last action in your thread. If that flag isn't set, you can assume it was aborted. As @Chris Shain points out below, you have to be careful where you put it, though, since in the case of a thread abort, you'll get a ThreadAbortException
in your thread, so if you put it in the finally
clause, it will get set even in the case of a thread abort.
Upvotes: 0
Reputation: 51339
Your original assertion is not correct. Consider:
public static void TestThreadAbort()
{
var t = new Thread(() => Thread.Sleep(50000));
t.Start();
t.Abort();
Thread.Sleep(50);
// Prints "Aborted"
Console.WriteLine(t.ThreadState);
}
Upvotes: 3
Reputation: 1525
When a thread is aborted . You get ThreadAbortException on your thread. This can help you in differentiating.
Upvotes: 0