My scenario:
a few BackgroundWorkers to perform various functions.
one of them, and only once, will have to execute to do a special work first before continue and letting other works to do their job.
I'm using Monitor.TryEnter: do this special work when it's true (locking is successful); when it's false, will wait for the lock to be released.
Problem is that this special work is done asynchronously. I have a listener, and the CompletedSpecialWork method will be called, but the Thread is different from the Thread where Monitor.TryEnter was performed (that is, the Thread holding(locking) the object). I need a way to be able to send a message to the original Thread asking to release the object.
I tried to have a static object of SynchronizationContext, but when I do threadHoldingLock = SynchronizationContext.Current it is null (it is being called from the BackgroundWorker that was able to hold the lock).
My question is: from this CompletedSpecialWork context/thread, how can I send a request to the original thread (holding the lock) to release the lock via Monitor.Exit? I need like a way to send a Invoke to the original thread with Monitor.Exit on it.
Try using either ManualResetEvent or AutoResetEvent.
These can be used to block one thread and then (via function call from a running thread into the blocked thread) allow the block to be reset.
They are syntactic sugar on top of a Semaphore but I like the simplified interface.
Good luck!
By their very nature synchronization objects like mutexes need to be released from the same thread that acquired a lock on them. It would pretty much make any kind of synchronization a crashy hit&miss affair if this requirement didn't exist and all your threads could just randomly release all locks from all threads.
You should look at Event objects to signal simple pulses between threads.
Related
Ok so lets say all I have is the reference of a System.Threading.Thread called thread A and I'm on another thread, lets say thread B. Now I need to execute a bit of code on thread A for a moment, then switch back. Using the reference I have, how can I Invoke thread A to do an action in it?
Well I'm making a c++/cli library. One of my objects has a thread affinity. I enter a method, I need to swap threads like you would in a Dispatcher.Invoke.
void AllegroSharp::Display::DrawToBackBuffer(BitmapImage^ image)
{
al_draw_bitmap(image->GetBitmap(), (float)image->Rect->Position->X, (float)image->Rect->Position->Y, 0);
}
DrawToBackBuffer gets called on thread B and al_draw_bitmap needs to be called on Thread A, which I have a reference to. How can I do this on thread A? Thread B is just some thread that c# spawned when I did a Task.Run in managed code.
Threads run one set of instructions from start to finish. If thread A is already running, it will execute whatever code it's been told to run from start to finish. You won't be able to change what it's running unless it is actively monitoring some shared memory for instructions on what to do next. Typically the way you implement this is by having a thread run in a loop and, inside that loop, check a message queue. Then have other threads add messages to that queue to give the looping thread work to do. There are a lot more details to make it work right, but that's the basic idea.
If, in your particular scenario, thread A is the application's GUI thread, this message passing mechanism is already set up for you, and you can use Control.Invoke (winforms) or Dispatcher.Invoke (WPF) to pass a unit of work to the GUI thread and wait for it to be completed.
Edit: this answer has been rendered less applicable by the addition of new information to the question. Ah well.
So I am thinking of an instance of a class where I want a thread to run for the life of the class, but terminate when the process that invoked the class is no longer running. This is not the case of a parent thread terminating a child, but a single spinning (in a wait loop perhaps) thread exiting gracefully without holding resources etc.
I think that in C++, you can tell the thread to terminate using a volatile bool from the destructor, however in C# the ~ is not a destructor it is a finalizer. I have not been able to successfully terminate a thread using the finalizer. Perhaps I am missing something there. I know that it is better practice is to have all threads die a natural death without signaling its termination, but it is just not efficient to be spawning a thread each time I need to do something. Yes I know about thread pools, but I think it would be better to have a single listener thread respond to calls to the class, and have it gracefully die when the class is put on the gc.
The real trick is, I think, can I know, or how do I know when the class that is running the thread is first placed on the gc. Is IDisposable what I am looking for? I am not using any unmanaged code here.
I think you basically have two sensible choices.
Choice One:
If you really don't have any unmanaged resources in use, then you can just let the system close your thread when the program closes. This is obviously the simplest solution.
You only have to worry if you are using objects which have dispose methods that should be called. That includes open files, but probably wouldn't include something like a font.
If you do this, you must ensure that the thread will be running as a "background" thread. The only difference between a background thread and a foreground thread is that when the program closes, all background threads will be automatically terminated - but foreground threads won't.
If you use a Task, by default it will be run as a background thread.
You definitely won't want to do this if your thread will be doing some IO to disk or doing anything else that mustn't be interrupted.
Choice Two:
Add a thread cancellation mechanism, using CancellationTokenSource and arrange to use it at program shutdown, and wait for the thread to exit.
In this case you won't really care whether the thread is foreground or background because you will be managing the program shutdown yourself, and the thread will be stopped properly before the program exits.
If you take this route, you can encapsulate the thread cancellation logic and other thread handling methods in a class that wraps the thread. Then you can add a Dispose() method so you can create the class inside a using block to ensure proper shutdown even in the face of exceptions.
I have taken this approach quite often, and it seems to work quite nicely.
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;
So my question is how to implement cancel/interrupt feature into all (I mean ALL) thread workers in your application in best and most elegant way?
It's not important if it's an HttpWebRequest, IO operation or calculation. User should have an possibility to cancel every action/thread at any moment.
Use .NET 4.0 Tasks with CancellationTokens - they are the new universal cancellation system.
User should have an possibility to
cancel every action/thread at any
moment.
Threading is a practice, not a design... and believe me it has been tried as a design, but it failed miserably. The basic problem with simply canceling any action at any moment is that in a multithreaded environment it's just evil! Imagine that you have a section of code guarded by a lock and you have two threads running in parallel:
Thread 1 acquires the lock.
Thread 2 waits until the lock is released so it can acquire it.
Thread 1 is canceled while it's holding the lock and it doesn't release the lock.
DEADLOCK: Thread 2 is waiting for the lock which will never be released.
This is the simplest example and technically we can take care of this situation in the design, i.e. automatically release any locks that the thread has acquired, but instead of locks think of object states, resource utilization, client dependencies, etc. If your thread is modifying a big object and it's canceled in the middle of the modification, then the state of the object may be inconsistent, the resource which you're utilizing might get hung up, the client depending on that thread might crash... there is a slew of things which can happen and there is simply no way to design for them. In this case you make it a practice to manage the threads: you ensure a safe cancellation of your threads.
Others have already mentioned various methods for starting threads that can be canceled, but I just wanted to touch on the principles. Even in the cases where there is a way to cancel your threads, you still have to keep in mind that you're responsible for determining the safest way to cancel your thread.
It's not important if it's an HttpWebRequest, IO operation or calculation.
I hope now you understand why it's the MOST important thing! Unless you specifically know what your thread is doing, then there is no safe way to automatically cancel it.
P.S.
One thing to remember is that if you don't want hanging threads then for each one of them you can set the Thread.IsBackground flag to true and they will automatically be closed when your application exits.
Your worker threads need a way to check with your main thread to see if they should keep going. One way is to share a static volatile bool that's set by your UI and periodically checked by the worker threads.
My preference is to create your own threads that run instances of a worker class that periodically invoke a callback method provided by your main thread. This callback returns a value that tells the worker to continue, pause, or stop.
Avoid the temptation to use Thread.Abort() to kill worker threads: Manipulating a thread from a different 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.