What is the effect of calling Thread.CurrentThread.Join(), and if/when would it make sense to call it?
Was it really
CurrentThread.Join()
that you saw in real code - which I kind of doubt, unless it's some hack to prevent other threads to join on the current thread - or was it
CurrentThread.Join(someTimeout)
The latter is equivalent to
Thread.Sleep(someTimeout)
except that joining on the current thread allows message pumping to continue if you are in a GUI / COM situation.
What is the effect of calling Thread.CurrentThread.Join()
You will block the execution of the current thread, and effectively dead lock it. It will cause the current thread to block until the current thread finishes, which will never happen.
, and if/when would it make sense to call it?
It really doesn't make sense to do this. You should never call this method in this manner.
On a side note, since you're using .NET 4, I would recommend avoiding using Thread.Join in general. Using the new Task/Task<T> classes is far nicer in many ways, as you can easily attach continuations (or always call Task.Wait() if you truly need to block).
It actually make sense in world of observable. Lets say you have a queue listener in main and you want to keep main thread running forever.
Instead of doing while(true) and put your code in the loop, last line you can write this. This way current thread will also be parent thread for other threads spawned within the application.
Think of it as entry point for app.
No, CurrentThread.Join() makes no sense
This could make your program stop running, making the thread A wait for thread A for example.
If you are making a unit test that tests if timers perform well in lets say a Windows Service and you use Thread.Sleep() statements with more as 60 seconds in it you can get ContextSwitch errors because the Thread.Sleep() is blocking the message pump.
If you are replacing those Thread.Sleep() statements in your unit test with Thread.CurrentThread.Join() then those ContextSwitch error will go away. So its a non blocking solution.
You could say Thread.CurrentThread.Join() is a better Thread.Sleep().
CurrentThread.Join() can be used to put the current thread to sleep until another thread interrupts it.
For example, you may have a server where the main method sets up a pool of other threads to handle incoming requests, passes a reference to it's current thread to a shutdown-trap, and then goes to sleep until it's time for the server to shut down.
This is not a terribly common pattern but it would be wrong to say that there is no case where you'd want your current thread to sleep until interrupted.
Related
I was trying to use AutoResetEvent.WaitOne() on a GUI thread hoping that it would not block the GUI thread completely and allow the GUI thread to keep pumping windows messages while it waits for a signal (similar to Thread.Wait()). I learned that wasn't a correct assumption.
So am looking for a way to be on the GUI Thread and wait for a thread to finish running (similar to using AutoResetEvent.WaitOne()) but keep the message pump flowing. (Please no DoEvents())
I guess the short question is: Is there a WAIT in .NET that pumps windows messages (especially "Paint" event) while it is waiting?
The CLR has a special workaround for calling WaitOne() on an STA thread. That is illegal, a thread that supports apartment threading is not allowed to block. That's very prone to cause deadlock. The CLR will in fact start taking over the duty of pumping messages, roughly similar to MsgWaitForMultipleObjects. Very roughly.
While this works to keep the basic plumbing of a UI thread alive, like painting, this is not ever something you want to do if you can avoid it. Quirky stuff can happen, not quite unlike using Application.DoEvents(), although the CLR code does try to minimize the damage that the re-entrancy can cause.
Big secret how they do this btw, it was intentionally omitted from the SSCLI20 distribution which is otherwise a very complete copy of the CLR code. Chris Brumme blogged about it, pretty impenetrable in his usual way, but with just waving his hands and not giving away any good secrets. The code itself is quite resistant to reverse engineering, it is large. The only common signs of it is finding it back in a stack trace from a programmer that's got a very hard problem to solve.
In other words, you are invoking a code path that's highly undocumented and poorly understood. Don't do it. It is fundamentally unnecessary, you can always invoke back to the UI thread and continue with the code that you've now got after the WaitOne() call. That's safe.
I don't know of any such thing that you're asking for. AFIK (as far as i know), you'll need to start a second background task or thread which waits for the AutoResetEvent to trigger in the background thread and in your UI thread, once you launch the task or 2nd thread, exit your method so it is free to do it's job of 'message pumping' as you put it.
So in this scenario, the background thread would then need to finish your processing once its AutoResetEvent is triggered to continue the processing.
I wanted to try my luck in threading with C#, I know a few things about threading in C.
So I just wanted to ask if i wanted to terminate a thread, I should do it with smt.Abort()
or it will "kill itself" after the function ends?
Also, is there something like pthread_exit() in C in C#?
Thread.Abort will "kill" the thread, but this is roughly equivalent to:
Scenario: You want to turn off your computer
Solution: You strap dynamite to your computer, light it, and run.
It's FAR better to trigger an "exit condition", either via CancellationTokenSource.Cancel, setting some (safely accessed) "is running" bool, etc., and calling Thread.Join. This is more like:
Scenario: You want to turn off your computer
Solution: You click start, shut down, and wait until the computer powers down.
You don't need to terminate a thread manually once the function has ended.
If you spawn up a thread to run a method, once the method has returned the thread will be shut down automatically as it has nothing further to execute.*
You can of course, manually abort a thread by simply calling Abort(), but this is pretty much un-recommended due to potential thread state corruption due to unreliable determination of where a thread is at in its current execution state. If you need to handle the killing of threads yourself, you may be best looking into using a CancellationToken. You could also read up on the Cancellation of Managed Threads article on MSDN.
** That is, unless, you're using a ThreadPool to perform your work. You shouldn't worry about aborting these threads as they're reused across different queued tasks.
Terminating a thread externally (from outside the thread) is a bad idea; you never know what the thread was in the middle of doing when you kill it asynchronously. In C#, if your thread function returns, the thread ends.
This MSDN article How to: Create and Terminate Threads (C# Programming Guide) has some notes and some sample code that you will probably find helpful.
Thread.Abort()
Thread.Join();
Thread = null;
I am using the class HttpListener as a web server. This server runs on a different thread.
At some point this server needs to run some code but it needs to be executed on the main thread. Is there an easy way of doing that?
Thanks!
The bigger question is:
Why do you need to run it on the parent thread? Is it UI Code modifying the UI? Do you need to be within that thread's context to gaurantee thread saftey?
It might be worth stepping back and re-evaluating your threading model, you may be trying to do things in the wrong place.
I Suggest you read This Excelent Free E-Book on C# Threading and learn about the alternate ways of inter-thread communication and look into the Dispatcher if you're using WPF, as it will help delegate events back to the UI Thread if that's what your intent is.
Quick & Dirty Solution Not really the best way
There's any number of ways to approach this, the simplest would probably to have a list of delegates to execute on the main thread. Each time your main thread spins, you lock the collection (unless you're using the multi-threaded collections) and copy out the delegates & clear the collection and release the lock.
Then you simply run them on the main thread.
The problem you'll run into is if you're using blocking on the main thread, your spin cycle will not pass across your delegates till your blocking stops. So if you're say, blocking while you wait for connections, your code will not run till a new person connects.
You could put the server's listen port on it's own thread to solve this.
To do something on the main thread, you will possibly want to inject it via Invoke(), or in the main loop will have some queue of things to do that will be injected from the 'other' threads, in this case HttpListener.
Your example seems similar to mine, where I have 300 threads handling stream ripping, and they are all 'calling' main thread by putting the string messages into the queue for it. It works like a charm. However, when I did try (I dared, just to see what will happen) to Invoke() from at least 30-ish threads to the main message loop, it was weird, to say the least.
Best: use simple Queue< something >, and enqueue it from the other thread, then dequeue it from the UI thread.
What is the difference between Thraed.Abort() and Thread.Interrupt(). How can I call them in a Thread Safe Manner.It would be helpful,if simple example is provided.
First of all, neither of these are good thread synchronization constructs.
First, Thread.Abort says "I don't care what you're doing, just stop doing it, and leave everything as it is right now". It's basically the programming way of saying "Hey, beat it". If your thread is having files open, those files will be left open until garbage collection gets around to finalizing your objects.
Thread.Abort should only ever be used, and even then probably not, in the case when the app domain that the thread is running inside is being torn down, preferably only when the process is being terminated.
Secondly, Thread.Interrupt is a rather strange beast. It basically says "I don't care what you're waiting for, stop waiting for it". The strange thing here is that if the thread isn't currently waiting for anything, it's instead "I don't care what you're going to wait for next, but when you do, stop waiting for it immediately".
Both of these are signs that you're imposing your will on a thread that wasn't designed to be told such things.
To abort a thread properly, the thread should periodically check some kind of flag, be it a simple volatile Boolean variable, or an event object. If the flag says "You should now terminate", the thread should terminate itself by returning from the methods in an orderly fashion.
To properly wake a thread, a thread should, in places where it has to wait for synchronization objects, include a "please stop waiting" object that it also waits on. So basically it would for either the object it needs becomes signaled, or the "please stop waiting" object becomes signaled, determine which one that did, and do the right thing.
So instead of Thread.Abort and Thread.Interrupt, you should write your threads using normal synchronization objects, like events, mutexes, semaphores, etc.
For the same reason, Thread.Suspend and Thread.Resume should be left alone, and they have also been obsoleted in the later versions of .NET.
Unless you're calling Abort or Interrupt on the currently executing thread (as ASP.NET does to terminate a request abruptly, for example) you basically can't call them in a thread-safe manner.
Use a WaitHandle or Monitor.Wait/Pulse to wait in a wakeable way. You should only abort other threads if you're tearing down the application, basically - as otherwise you can end up in an unknown state.
See my article on graceful thread termination for an example of how to do this nicely.
Thread.Abort() raises a ThreadAbortException on the target thread. It's intent to generally to force the thread to terminate. It is not a recommended practice for stopping a thread's processing.
Thread.Interrupt() interrupts a thread that is in WaitSleepJoin state - essentially blocking on a resource like a WaitHandle. This allows the caller to unblock the thread.
Neither is really "thread-safe" - in the sense that they are specifically intended to affect the behavior of threads in a way that is hard to predict.
It's generally recommended to use synchronization objects (like WaitHandles or Semaphores) to allows threads to safely synchronize with one another.
The difference between Abort and Interrupt is that while they will both throw an exception (ThreadAbortException and ThreadInterruptException), calling Abort will rethrow the exception at the end of the catch block and will make sure to end your running thread.
So Thread.Sleep() is bad (http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx).
Is there any recommended alternative to simulating a pause in execution of a program? Eg a loop? Although I suppose this involves a lot of overhead in initialising variables, checking the bool condition, etc.
Thanks
If you are only going to simulate a pause (as in for test purposes), I think Thread.Sleep is a perfectly valid approach. On the other hand, if you are actually waiting for something, some sort of thread-safe signalling mechanism would be better (check the types that inherits WaitHandle).
simulating a pause
"Simulating" sounds like something you would only do in debugging. Thread.Sleep should be fine.
The main problem with Sleep is that usually you should be waiting for something specific to occur rather than waiting for an arbitrary delay.
The other thing to watch out for is calling Thread.Sleep from a UI thread, which will make the UI unresponsive. Better to disable the parts of the UI that you do not want the user to interact with and then use a Timer control to implement the delay.
From what you said, you're trying to simulate a pause in execution.
Thread.Sleep is perfectly valid for that. Even the article you linked starts with:
Thread.Sleep has it's use: simulating lengthy operations while testing/debugging on an MTA thread.
I don't agree with the assessment that Thread.Sleep() is "bad". It depends on the situation.
In a console mode program, it might be perfectly appropriate to sleep the thread if you're waiting for something. Perhaps even in a loop: Check the condition, sleep for a bit if it's not satisfied, repeat.
In a graphical program however, normally you would not sleep on the main (GUI) thread. This is because these days GUI interfaces are designed with a single interactive thread. If you sleep on that thread, your whole GUI will appear to "lock up" for the time that you're sleeping. A better situation might be to use some kind of timer (all GUI frameworks have such a concept).
One thing you do not want to do is write a loop that continually checks for some condition to be true, without even sleeping. This will cause one CPU to run up to 100% because the CPU wants to get its work done as fast as possible. Not only is this unexpected from a user point of view, but it's unfriendly because such activity can starve the process that you're actually waiting for of enough cycles to get its work done!
If you're waiting for some code or event to occur, you can use wait handles.
While the article itself is debatable, I agree with its starting sentence, which addresses your concern
Thread.Sleep has it's use: simulating
lengthy operations while
testing/debugging on an MTA thread.
In .NET there's no other reason to use
it.
I believe that's what you are asking about (simulating pauses) and is the main use of Thread.Sleep()
I use the System.Timers:
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
I believe Raymond Chen has recommended to set the thread priority lower
http://blogs.msdn.com/oldnewthing/archive/2009/07/27/9849503.aspx
I don't quite understand why you want to pause every so often. Why not just do the work at low priority? When there are more important things to do, your background thread will stop doing whatever it's doing. When there is an available CPU, then your background thread will do its thing as fast as it can (until something with higher priority arrives).
I would be willing to bet that in the majority of cases where a programmer thinks of using Thread.Sleep(), some simple code that uses events would work very well.