Can BackgroundWorker Thread be Killed like other threads..? - c#

I just want to know how we can kill the BackgroundWorker Thread once it finished up with its associated tasks.
Is there any method like Kill or Abort or something else which can help?

Why are you worried about closing the thread after the task is already completed?
The thread is cleaned up in garbage collection. Calling Dispose() will help it probably be cleaned up sooner and is 'best practice'.
BackgroundWorker tasks are meant to be used on WinForms or using ThreadPool.QueueUserWorkItem(...) which will handle the lifecycle of the thread automatically internally.
See this related question: How to "kill" background worker completely?

No, you can't in general kill the thread that the BackgroundWorker was running on. That thread is part of ThreadPool. The ThreadPool manages the threads and decides when it should allocate more or get rid of some. You don't need to worry about killing the thread.
Which shouldn't be a problem. It's not like the thread is using any CPU time while it's idle. The small amount of system resources it's occupying won't be noticed.

Related

How do I end a thread gracefully at the point when the calling process exits or is killed?

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.

How to terminate a thread in C#?

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;

Why is it bad to pause/abort threads?

My model of how threads work is that some ThreadManager gives each thread a turn. When it's a thread's turn, it gets to execute a few lines of code.
To pause a thread, couldn't one just have the ThreadManager (momentarily) stop allowing that thread to have a turn?
To abort a thread, couldn't the ThreadManager just never give that thread another turn?
What's the problem?
Quote from MSDN about pausing threads:
You have no way of knowing what code a
thread is executing when you suspend
it. If you suspend a thread while it
holds locks during a security
permission evaluation, other threads
in the AppDomain might be blocked. If
you suspend a thread while it is
executing a class constructor, other
threads in the AppDomain that attempt
to use that class are blocked.
Deadlocks can occur very easily.
Aborted thread can lead to unpredicted circumstances. There is a good article about this: http://www.bluebytesoftware.com/blog/2009/03/13/ManagedCodeAndAsynchronousExceptionHardening.aspx
I agree with Alex, but to elaborate further, if you need to "pause" a thread, it will probably be better to look at some sort of locking mechanism like Semaphores, Mutexes, or one of the many other ones available.
But, without knowing your code, Windows is a preemptive multitasking environment. Usually this is not needed, just let your threads run and the underlying OS and scheduler will make sure all your tasks get a fair turn.

Impossible to Kill Threads waiting for Interop objects

I've been searching through google a little bit and quite fast discovered that there are no solution on aborting a thread which is using COM Interop and is in a "wait for interop event" state. The Thread.Abort() will just put the thread into "AbortRequested" mode, which, quite franky, isn't much.
The results is me not being able to close my application. The process remains in the taskman because of the a childThread.
Anyone know if it is possible to Force Abort a thread?
Have you tried setting "IsBackground=True" on the thread? Threads marked as background will be cleaned up when the process is exiting, whereas process exit will wait for "foreground" threads.

Best way: to implement an interrupt/cancel feature for all your threaded workers

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.

Categories

Resources