is there a way to abort threads created with QueueUserWorkItem?
Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?
You don't need to abort them. When your application exits, .NET will kill any threads with IsBackground = true. The .NET threadpool has all its threads set to IsBackground = true, so you don't have to worry about it.
Now if you're creating threads by newing up the Thread class, then you'll either need to abort them or set their IsBackground property to true.
However, if you are using unmanaged
resources in those threads, you may
end up in a lot of trouble.
That would rather depend how you were using them - if these unmanaged resources were properly wrapped then they'd be dealt with by their wrapper finalization regardless of the mechanism used to kill threads which had referenced them. And unmanaged resources are freed up by the OS when an app exits anyway.
There is a general feeling that (Windows) applications spend much too much time trying to clean-up on app shutdown - often involving paging-in huge amounts of memory just so that it can be discarded again (or paging-in code which runs around freeing unmangaged objects which the OS would deal with anyway).
The threadpool uses background threads. Hence, they will all be closed automatically when the application exits.
If you want to abort a thread yourself, you'll have to either manage the thread yourself (so you can call Thread.Abort() on the thread object) or you will have to set up some form of notification mechanism which will let you tell the thread that it should abort itself.
Yes, they will. However, if you are using unmanaged resources in those threads, you may end up in a lot of trouble.
yeah, they are background, but f.ex if you have application where you use ThreadPool for some kinda multiple downloading or stuff, and you want to stop them, how do you stop ? my suggestion would be:
exit thread asap, f.ex
bool stop = false;
void doDownloadWork(object s)
{
if (!stop)
{
DownloadLink((String)s, location);
}
}
and if you set stop = true, second (currently in queue) threads automatically exit, after queue threads finishes it process.
According to Lukas Ĺ alkauskas' answer.
But you should use:
volatile bool stop = false;
to tell the compiler this variable is used by several threads.
Related
I'm starting multiple threads and would like to know when any of then finishes. I know the following code:
foreach (Thread t in threads)
t.Join();
But it will only wait for all threads together. That's much too late. I need to know when one thread finishes, even when other threads are still running. I'm looking for something equivalent to WaitAny only for threads. But I can't add code to all threads I'm monitoring, so using signals or other synchronisation objects is not an option.
Some clarification: I'm working on a logging/tracing tool that should log the application's activity. I can insert log statements when a thread starts, but I can't insert a log statement on every possible way out of the thread (multiple exit points, exceptions etc.). So I'd like to register the new thread and then be notified when it finishes to write a log entry. I could asynchronously Join on every thread, but that means a second thread for every monitored thread which may seem a bit much overhead. Threads are used by various means, be it a BackgroundWorker, Task or pool thread. In its essence, it's a thread and I'd like to know when it's done. The exact thread mechanism is defined by the application, not the logging solution.
Instead of Threads use Tasks. It has the method WaitAny.
Task.WaitAny
As you can read here,
More efficient and more scalable use of system resources.
More programmatic control than is possible with a thread or work item.
In my opinion WaitHandle.WaitAny is the best solution, since you don't like to use it for some xyz reason you can try something like this.
Take the advantage of Thread.Join(int) method which takes millisecond timeout and returns true when thread is terminated or false when timed out.
List<Thread> threads = new List<Thread>();
while (!threads.Any(x=> x.Join(100)))
{
}
You can alter the timeout of Join If you know how long it will take.
My answer is based on your clarification that all you have is Thread.Current. Disclaimer: IMO, what you're trying to do is a hack, thus my idea by all means is a hack too.
So, use reflection to obtain the set of native Win32 handles for your desired threads. Your are looking for Thread.GetNativeHandle method which is internal, so you call it like thread.GetType().InvokeMember("GetNativeHandle", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, ...). Use a reflection tool of your choice or Framework sources to learn more about it. Once you've got the handles, go on with one of the following options:
Set up your own implementation of SynchronizationContext (derive from it) and use SynchronizationContext.WaitHelper(waitAll: false) to wait for your unmanaged handles.
Use the raw Win32 API like WaitForMultipleObjects or CoWaitForMultipleObjects (depending on whether you need to pump messages).
Perform the wait on a separate child or pool thread.
[EDITED] Depending on the execution environment of your target threads, this hack may not work, because one-to-one mapping between managed and unmanaged threads is not guaranteed:
It is possible to determine the Windows thread that is executing the code for a managed thread and to retrieve its handle. However, it still doesn't make sense to call the SetThreadAffinityMask function for this Windows thread, because the managed scheduler can continue the execution of a managed thread in another Windows thread.
It appears however, this may be an implication only for custom CLR hosts. Also, it appears to be possible to control managed thread affinity with Thread.BeginThreadAffinity and Thread.EndThreadAffinity.
You could use a background worker for your working threads.
Then hook all the RunWorkerCompleted events to a method that will wait for them.
If you want that to be synched to the code where you're currently waiting for the join, then the problem is reduced to just synchronizing that single event method to that place in code.
Better yet, I'd suggest to do what you're doing asynchronously without blocking, and just do what you want in the event.
Would you consider wrapping your thread invocations with another 'logging' thread? That way you could log synchronously before & after the thread run.
Something like this pseudo-code:
int threadLogger(<parms>) {
log("starting thread");
retcode = ActualThreadBody(<parms>);
log("exiting thread");
return retcode;
}
If you have more information on the thread started, you could log that as well.
You could also take the thread function as a parameter in the case where you have multiple types of threads to start, which it sounds like you do.
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.
Pseudo-situation: have a class (let's say BackgroundMagic), and it has Start() and Stop() methods. The work in this class is done by one single thread, and is simply a short loop every X milliseconds.
Which of these options is better, as far as managing the stopping/starting? Can't decide which road to take.
The first time Start() is called, initialize and start the thread with IsBackground = true. Use a simple bool flag to indicate on each loop around whether it should actually do any work, or just sleep. After initial initialization, let Stop() and Start() simply control the bool flag. The thread will just be stopped and cleaned up by the runtime since IsBackground = true when the app exits.
Forcefully abort/join/interrupt/whatever on Stop, and recreate the thread again on Start(), not leaving the thread lying around.
... or any better/cleaner ways of doing this?
Neither! Use a Thread Pool!
Thread creation is fairly expensive, so the standard "industrial-strength" way to do this is to control the thread with a flag. For a larger-scale variant on the same idea, consider the thread pools that e.g. Apache uses to manage thousands of threads without a lot of explicit state or a painful performance hit.
So in the abstract, I'd vote for your option #1. But if performance isn't a concern and the option #2 code is easier to reason about, go for it.
A mutex or semaphore would be a better option than a simple boolean flag, because it doesn't require checking the state of the flag repeatedly. Simply block on the mutex/semaphore, and when you want the thread to run, release the mutex/semaphore and the thread will run once.
The thread pool is not appropriate for long-running tasks. The thread pool is ideal for short tasks where the overhead of thread creation increases the overhead of the operation by a large percentage. This is also true of the TPL (Task Parallel Library) in the .NET 4 framework.
Using a thread dedicated to do this work is probably a good idea, but how you manage it can be a big deal. If you simply do a Thread.Sleep between checking for work then that is less effective because now you have the thread spinning for no good reason. This is called a spin lock (kind of) and is only effective if you know the resource you are waiting for is going to release the lock very soon. It would be a far better idea to use an AutoResetEvent. This way the thread only wakes up because the producer thread signaled that there is work to do. This has the advantage of not wasting CPU resources to schedule the thread if there is nothing to do and it allows for less delay between the producer and consumer.
To answer your question directly, yes you can use some kind of bool to gracefully shutdown the thread (I would mark it as volatile though). This is much better than aborting the thread!
See:
http://www.yoda.arachsys.com/csharp/threads/threadpool.shtml
http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx
http://msdn.microsoft.com/en-us/library/x13ttww7(v=VS.100).aspx
You can also use a bool flag to indicate if the thread should stop. Which gives you your interrupt and stop code. So two bools one for if there is work and one to stop the loop.
The other thing you could consider is using the Dispose pattern and cleaning up the thread when the object is disposed.
I would use the bool flag, but you need to be sure it is either correctly locked or only set from one thread. Your loop should look like this
while (true)
{
if (shouldSleep)
{
Thread.Sleep(interval);
continue;
}
doSomeWork();
if (shouldCancel)
{
CleanUpResources();
break;
}
}
This makes sure you can send the thread to sleep but also correctly terminate it. Killing a thread is never a good idea if you can avoid it as the thread doesn't have a chance to clean up any resources used. You need to decide on an appropriate sleep interval though. It will determine the latency your thread needs to start up.
The second option is rather expensive, thread creation involves some OS resources and startup time is also considerable. If thread recreation won't happen often and the amount of work performed is large enough this would be reasonable. You can avoid the complexity involved in the loop approach.