Can a ThreadAbortException be raised during Thread.Sleep? - c#

Can Thread.Abort interrupt a thread that is sleeping (using, say, Thread.Sleep(TimeSpan.FromDays(40)) ? Or will it wait until the sleep time span has expired ?
(Remarks: FromDays(40) is of course a joke. And I know Thread.Abort is not a recommended way to stop a thread, I'm working with legacy code that I don't want to refactor for now.)

Code is worth a thousand words:
public static void Main(string[] args)
{
var sleepy = new Thread(() => Thread.Sleep(20000));
sleepy.Start();
Thread.Sleep(100);
sleepy.Abort();
sleepy.Join();
}
The program ends before the sleep time is exhausted.

You can abort the thread from another thread only. That is, you should store the Thread reference somewhere and then call .Abort from a thread other than the one which is sleeping.

Related

Why does the main thread's output come first in C#?

I wrote this little program:
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(WriteX);
t.Start();
for (int i = 0; i < 1000; i++)
{
Console.Write("O");
}
}
private static void WriteX()
{
for (int i = 0; i < 1000; i++)
{
Console.Write(".");
}
}
}
I ran it about fifty times, and the first character on the console was always "O". It is weird for me, because the t thread starts first then the main continues.
Is there any explanation for this?
This is probably because Thread.Start first causes the change of state of thread on which it is called and OS schedules it for execution whereas the main thread is already running and does not need these two steps. This is probably the reason that the statement in main thread executes first rather the one in the newly created thread. Keep in mind the sequence of thread execution is not guaranteed.
Thread.Start Method
1) Thread.Start Method Causes the operating system to change the state of
the current instance to ThreadState.Running.
2) Once a thread is in the ThreadState.Running state, the operating
system can schedule it for execution. The thread begins executing at
the first line of the method represented by the ThreadStart
Edit It seems to me that representing this in graphical form will make this more clear and understandable. I tried to show the sequence of thread execution in diagram below.
You say:
"It is weird for me, because the t thread starts first then the main continues.".
This is not true. The "main" tread is already running. When t.Start(); is executed, the OS is told t is in the running state. The OS will then schedule execution time for the thread "soon". This is something else than the OS is instructed to stop execution of this thread until thread t is started. In other words, when Start returns, there is no guarantee that the thread has already started executing.
More of an advice than not an answer:
(Please note, that I see no real-life use for what you are trying to achieve, so I treat your problem as a thought experiment/proof of a concept not explained in detail.)
If you want your threads to "race" for control, don't give your main thread a head start! Creating a thread has some overhead and your main thread is already created (since it creates your other thread). If you are looking for a mostly equal chance for both of your main and worker thread, you should wait for your worker thread to be created in the main thread and wait for the main thread to start the race in your background thread. This can be achived by synch objects.
In practice it would look like this:
You should declare two ManualResetEvents which are visible for both your main- and background thread like this:
private static ManualResetEvent backgroundThreadReady = new ManualResetEvent(false);
private static ManualResetEvent startThreadRace = new ManualResetEvent(false);
Then in your main thread, you should wait for your thread being initialized like:
static void Main(string[] args)
{
Thread t = new Thread(WriteX);
t.Start();
backgroundThreadReady.WaitOne(); // wait for background thread to be ready
startThreadRace.Set(); // signal your background thread to start the race
for (int i = 0; i < 1000; i++)
{
Console.Write("O");
}
}
And in your thread:
private static void WriteX()
{
backgroundThreadReady.Set(); // inform your main thread that this thread is ready for the race
startThreadRace.WaitOne(); // wait 'till the main thread starts the race
for (int i = 0; i < 1000; i++)
{
Console.Write(".");
}
}
Please note that I could have used other waitable sync objects (mutex, autoreset event, even a critical section lock with some hack, I've just choose the simplest, fastest solution which can be extended easily).
Your code is non deterministic. Your code contains no thread primitives that would schedule priority of one thread over another or for one thread to wait for another.
Main process continue its next instructions set after invoking the thread ,It will take time to start thread method as light process.
It basically needs time to start the thread up. You are running the thread code at the same time as the rest of the first method. So taking into account the time it takes to start the thread and then get to the point where it is writing the "." does that make sense?
If you have a sort of reset button in your app to start everything again (without exiting) you may find that the first character is the "." because the thread will already exist.
There is only one reason why the main thread will finish before the created thread and that is because it takes time to start a thread. The only time you would use threads to speed up a program is when 2 tasks can be run at the exact same time. If you want to make the second loop finish first , take a look at Parallel.For loops in c#... these will run each loop in the for loop at the same time (not all of them but as much as your PC can handle)

Observing Different outputs in Threads

I am exploring threading concept,
Every time when i tried to execute the below code, I am getting different output.
I am starting ThreadOne first, But why is ThreadTwo getting started.
Why am I getting Different output? Can someone explain in Detail?
Thanks In Advance.
static Object newLockobj = new Object();
static void Main(string[] args)
{
Thread tobj1 = new Thread(ThreadOne);
Thread tobj2 = new Thread(ThreadTwo);
tobj1.Start();
tobj2.Start();
Console.ReadLine();
}
static void ThreadOne()
{
Console.WriteLine("Thread One Entered");
lock (newLockobj)
{
Console.WriteLine("Thread 1 started");
Thread.Sleep(2000);
Console.WriteLine("Thread 1 ended");
}
}
static void ThreadTwo()
{
Console.WriteLine("Thread Two Entered");
lock (newLockobj)
{
Console.WriteLine("Thread 2 started");
Thread.Sleep(1000);
Console.WriteLine("Thread 2 ended");
}
}
This is a basic examle for Concurrency. Once you call the .Start() method on a thread object, it starts getting executed independent of the thread that started it. What your programm is doing:
Create the thread objects
Start tobj1 (the thread is not executed directly, but once the scheduler finds a place to put it)
Start tobj2 (the thread is again not executed directly)
The scheduler is responsible to tell the processor which process and which thread to execute. The order in which the threads are started is of no importance.
As soon as one thread starts, he prints the first line ("Thread X Entered"). The Lock is a synchronization statement. Since both threads sync on the same object instance, they cannot enter the Lock block both (Mutual Exclusion). The Lock statement only ensures that the process can work in the critical section without the other process working it his critical section. As you see in your right output, a thread can be interrupted although he is in his critical section ("Thread 2 started", "Thread One Entered", "..."). "Thread One", however, is not allowed to his critical section since the other thread did not release the lock yet.
This is in the heart of threads programming. While you have control over which thread you want to start first, the CPU is not obliged to follow your order of events. During the execution of one thread the CPU is guaranteed to follow you order of code execution as per your programming. When it comes to scheduling different threads, the CPU will follow its own logic and sometimes that logic can seem like random behavior. It will allocate processing time to different threads as it sees fit.
I suggest you read up more on threads programming as not fully understanding this concept and appreciating it's potential pitfalls will lead to many days of hair pulling and possible deadlocks :)
Just google: c# threading. You will get plenty of good resources!

Does Thread.Sleep affect the ThreadPool?

I need to control one thread for my own purposes: calculating, waiting, reporting, etc...
In all other cases I'm using the ThreadPool or TaskEx.
In debugger, when I'm doing Thread.Sleep(), I notice that some parts of the UI are becoming less responsible. Though, without debugger seems to work fine.
The question is: If I'm creating new Thread and Sleep()'ing it, can it affect ThreadPool/Tasks?
EDIT: here are code samples:
One random place in my app:
ThreadPool.QueueUserWorkItem((state) =>
{
LoadImageSource(imageUri, imageSourceRef);
});
Another random place in my app:
var parsedResult = await TaskEx.Run(() => JsonConvert.DeserializeObject<PocoProductItem>(resultString, Constants.JsonSerializerSettings));
My ConcurrentQueue (modified, original is taken from here):
Creation of thread for Queue needs:
public void Process(T request, bool Async = true, bool isRecurssive = false)
{
if (processThread == null || !processThread.IsAlive)
{
processThread = new Thread(ProcessQueue);
processThread.Name = "Process thread # " + Environment.TickCount;
processThread.Start();
}
If one of the Tasks reports some networking problems, i want this thread to wait a bit
if (ProcessRequest(requestToProcess, true))
{
RequestQueue.Dequeue();
}
else
{
DoWhenTaskReturnedFalse();
Thread.Sleep(3000);
}
So, the question one more time: can Thread.Sleep(3000);, called from new Thread(ProcessQueue);, affect ThreadPool or TaskEx.Run() ?
Assuming that the thread you put on sleep was obtained from thread pool then surely it does affect the thread pool. If you explicitly say that the thread should sleep then it cannot be reused by the thread pool during this time. This may cause the thread pool to spawn new threads if there are some jobs awaiting to be scheduled. Creating a new thread is always expensive - threads are system resources.
You can however look at Task.Delay method (along with async and await) that suspends executing code in a more intelligent way - allowing the thread to be reused during waiting.
Refer to this Thread.Sleep vs. Task.Delay article.
Thread.Sleep() affects the thread it's called from, if you're calling Thread.Sleep() in a ThreadPool thread and trying to queue up more it may be hitting the max count of ThreadPool threads and waiting for a thread to finish before executing another.
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads.aspx
No, the Thread.Sleep() is only on the current thread. Thread.Sleep(int32) documentation:
The number of milliseconds for which the thread is suspended.

Calling thread.sleep() while waiting for a new thread to spawn

I suppose this question can be boiled down to "SpinWait vs. Block?", but I figured there may be a more interesting answer as to why nearly every C# threading tutorial suggests the following call:
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.Start()
while (!newThread.isAlive()) ;
Thread.Sleep(1); // Allow the new thread to do some work
As opposed to blocking like so:
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.Start()
while (!newThread.isAlive()) Thread.Sleep(1);
Thread.Sleep(1); // Allow the new thread to do some work
My very brute-force testing (surrounding the while loop with calls to DateTime.Ticks) doesn't really reveal anything (says the difference is 0 ticks in both instances).
Is the thread creation process short enough that spinning is more efficient? Or do most tutorials suggest spinning because it's slightly more elegant and the time difference is negligible?
I don't know why you'd use either- off the top of my head, I can't think of any use case for blocking the calling thread until the new thread is alive, since being "Alive" doesn't mean that it has executed anything. If you need to wait for some code to have been run in the new thread before proceeding on the calling thread, you'd want to use a WaitHandle or SpinLock.
You can make the thread set an event when it starts and the main thread to wait on the event. no spinwait no too long sleeping.
This an article explains the use of SpinWait and also mentions different types of Sleep http://www.emadomara.com/2011/08/spinwait-and-lock-free-code.html

Multi threading question

I would like to invoke heavy duty method dowork on a separate thread and kill it if its taking longer than 3 seconds. Is there any problem with the following code?
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("starting new thread");
Thread t = new Thread(new ThreadStart(dowork));
t.Start();
DateTime start = DateTime.Now;
TimeSpan span = DateTime.Now.Subtract(start);
bool wait = true;
while (wait == true)
{
if (span.Seconds > 3)
{
t.Abort();
wait = false;
}
span = DateTime.Now.Subtract(start);
}
Console.WriteLine("ending new thread after seconds = {0}", span.Seconds);
Console.WriteLine("all done");
Console.ReadLine();
}
static void dowork()
{
Console.WriteLine("doing heavy work inside hello");
Thread.Sleep(7000);
Console.WriteLine("*** finished**** doing heavy work inside hello");
}
}
This is a very bad programming practice. Do not start up threads that you cannot shut down cleanly. The code which starts the thread and the code which runs the thread should have some well-defined mechanism by which they can communicate. There are many such mechanisms; for example, the worker thread could periodically ask the owner thread "should I keep going?" The worker thread could periodically check a threadsafe field that says whether to halt soon. And so on.
If you are starting up work on a new thread and you do not know what it is doing or how long it is going to take, then you are playing with fire. Particularly if that thread code could be hostile and actively resisting being taken down. There is no guarantee whatsoever that aborting a thread does anything at all; if you are clever then you can write code that makes threads that are resistant to thread aborts.
If you're in that situation, the right thing to do is to start up the code in a new process, not a new thread, and then shut down the process when it takes too long.
If it were me, I'd use the Thread.Join() overload that takes a milliseconds parameter. (Or the one that takes a TimeSpan.) It's cleaner and involves fewer lines of code.
t.Start();
if (!t.Join(3000))
t.Abort();
Or, like Matti said, put the timing logic inside threaded process and have it self-destruct.
I think you need to learn about Thread.Join(int). It will attempt to join with a thread and after a specified timeout it'll exit, upon which you can call Thread.Abort().

Categories

Resources