killing a thread which is in blocking state - c#

I have a thread which blocks itself on some lock.Now For some condition I want to kill the thread in c#.
But the thing is that in thread.abort does not guarantees that it will kill the thread.

If you really want a guarantee of thread death, your best option is to start a new process.
There is an excellent thread that discusses many of the possible pitfalls of thread.abort here.

Assuming you want to kill the thread in a deterministic way when it encounters deadlock . Right ?
Yes thread abort does not guarantee termination but it is almost always a bad idea to use Thread.Abort.
If there was a way to kill the thread instantaneously it can lead to bigger problems . If this thread has taken lock on some resource , is in the middle of some uncommitted transaction etc ,and the thread holding these resource is abruptly killed no other thread can work on these resources.
Best suggestion I can give is is to fix the deadlock issue rather than masking it.

Related

Starting new theard from another thread and abort it C#

if i do somtheing like this:
new Thread(DoWork).Start();
void DoWork(){new Thread(DoMoreWork).Start();}
and i aborting the first thread that run DoWork is DoMoreWork also will aborted?
if not how can i abort the sec thread (DoMoreWork)?
Thanks!
Update:
The problem that I run script with Microsoft.Scripting and for this I start a new thread that call Execute() method from Microsot.Scripting and I want to be able to abort the script. I can abort my thread but I don't know which thread Execute create to run the script.
Aborting the "parent" thread will not stop the "child".
Using Thread.Abort is a bad idea. you should design your thread to exit gracefully: see the answers to this question for example.
If you design your threads to exit gracefully (for example when you signal an event), this will also allow you to kill both threads.
this is a bad design...
you should not do that because if the second thread hangs also the first will not close and your GC will not clean resources AKA deadlock
threads are meant to run in parallel and sync not in a hierarchy.
there you can find a good guide to .net threading:
http://www.albahari.com/threading/

Thread: How to re-start thread once completed?

I have a method void DoWork(object input) that takes roughly 5 seconds to complete. I have read that Thread is better suited than ThreadPool for these longer operations but I have encountered a problem.
I click a button which calls threadRun.Start(input) which runs and completes fine. I click the button again and receive the following exception:
Thread is running or terminated; it cannot restart.
Can you not "reuse" a Thread? Should I use ThreadPool? Why is Thread "better suited for longer operations" compared to ThreadPool? If you can't reuse a thread, why use it at all (i.e. what advantages does it offer)?
Can you not "reuse" a Thread?
You can. But you have to code the thread not to terminate but to instead wait for more work. That's what a thread pool does.
Should I use ThreadPool?
If you want to re-use a thread, yes.
Why is Thread "better suited for longer operations" compared to ThreadPool?
Imagine a thread pool that is serving a large number of quick operations. You don't want to have too many threads, because the computer can only do so many things at a time. Each long operation you make the thread pool do ties up a thread from the pool. So the pool either has to have lots of extra threads or may run short of threads. Neither leads to an efficient thread pool design.
For longer operations, the overhead of creating and destroying a thread is very small in comparison to the cost of the operation. So the normal downside of using a thread just for the operation doesn't apply.
If you can't reuse a thread, why use it at all (i.e. what advantages does it offer)?
I'm assuming you mean using a thread dedicated to a job that then terminates over using a thread pool. The advantage is that the number of threads will always equal the number of jobs this way. This means you have to create a thread every time you start a job and destroy a thread every time you finish one, but you never have extra threads nor do you ever run short on threads. (This can be a good thing with I/O bound threads but can be a bad thing if most threads are CPU bound most of the time.)
Thread.Start documentation says:
Once the thread terminates, it cannot be restarted with another call
to Start.
Threads are not reusable. I have already faced this problem a while ago, the solution was to create a new Thread instance whenever needed.
It looks like this by by design.
I encountered the same problem and the only solution I could find was to recreate the thread. In my case I wasn't restarting the thread very often so I didn't look any further.
A search now has turned up this thread on social.msdn where the accepted answer states:
a stopped or aborted thread cannot be stated again.
The MSDN repeat this as well:
trying to restart an aborted thread by calling Start on a thread that has terminated throws a ThreadStateException.
As the message states, you cannot restart the thread. You can simply create a new thread for your next operation. Or, you might consider a design where the background thread keeps working until it completes all of your tasks, rather than launch a new thread for each one.
for(;;){} or while(true){} are useful constructs to 'reuse' a thread. Typically, the thread waits on some synchronization object at the top of these loops. In your example, you could wait on an event or semaphore and signal it from your button OnClick() handler.
It's just in background mode. It sounds like you need to use the ThreadPool because re-starting and re-creating Thread objects are very expensive operations. If you have a long running job that may last longer than your main process, then consider the use of a Windows Service.

C# threading deadlock

I have a multi-threaded program in C#. What is the best way to prevent deadlock in practice?
Is it timedlock?
Also, what is the best tool available to help detect and prevent the deadlock?
Thank you very much.
Deadlocks typically occur in a few scenarios:
You are using several locks and not locking/unlocking them in the correct order. Hence, you may create a situation where a thread holds lock A and needs lock B, and another thread needs lock A and holds lock B. Neither of them can proceed. This is because each thread is locking in a different order.
When using a reentrant lock and locking it more times than you are unlocking it. See this related question: why does the following code result in deadlock
When using Monitor.Wait/Monitor.Pulse as a signaling mechanism, but the thread that must call Wait does not manage to reach the call by the time the other thread has called Pulse and the signal is lost. You can use the AutoResetEvent for a persistent signal.
You have a worker thread polling a flag to know when to stop. The main thread sets the flag and attempts to join the worker thread, but you forgot to make the flag volatile.
It's not C# specific. You should always acquired in some well-defined order.
There is much information in internet, for example, you might take a look here
http://www.javamex.com/tutorials/threads/deadlock.shtml

How to close NHibenrate session when using the ThreadPool?

Since threads are reused over and over by the ThreadPool I can't tell when to close NHibernate sessions for each thread to release used up resources.
Should I spawn my own threads (to ensure they are unique) or there is a better way to do this using the ThreadPool?
I fail to see the problem. You might to have to elaborate or add some code in your question.
Each thread has it's own method. Simply allocate the session in the beginning of the method and clean it up in the end. The same applies when you are using a thread pool thread.
Don't forget to wrap all thread code in a try/catch, or your application will crash if an exception is unhandled.
I'd have it set up so that there is one session per thread. This is probably the easiest way to make sure that you don't run into issues where you have a thread terminating a session that is in use by another thread.

Threads pausing and resuming c#

I've got several threads ,how can I pause/resume them?
From duplicate question:
How can i pause 5 threads, and to remember their status. Because one of them is eating another is thinking, etc.
If you're using System.Threading.Thread, then you can call Suspend and Resume. This, however is not recommended. There's no telling what a thread might be doing when you call Suspend. If you call Suspend while the thread holds a lock, for example, or has a file open for exclusive access, nothing else will be able to access the locked resource.
As the documentation for Thread.Suspend says:
Do not use the Suspend and Resume
methods to synchronize the activities
of 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.
Typically, you control threads' activity using synchronization primitives like events. A thread will wait on an event (look into AutoResetEvent and ManualResetEvent). Or, if a thread is servicing a queue, you'll use something like BlockingCollection so that the thread can wait for something to be put into the queue. All of these non-busy wait techniques are much better than arbitrarily suspending and restarting a thread, and don't suffer from the potential disastrous consequences.
Have a look at Monitor.Wait and Monitor.Pulse in the first instance- Marc Gravell has a nice example used in a queue here.
In it quite likely that you want to consider using a Producer/Consumer queue.
You have to use synchronisation techniques
MSDN Thread Synchronization
In the main thread:
ManualResetEvent re = new ManualResetEvent(true);
In all the threads, at "strategic" points:
re.WaitOne();
In the main thread, to stop the threads:
re.Reset();
and to restart:
re.Set();
You can use Suspend() and Resume().
http://msdn.microsoft.com/en-us/library/system.threading.thread.resume.aspx
http://msdn.microsoft.com/en-us/library/system.threading.thread.suspend.aspx
You can also read:
What are alternative ways to suspend and resume a thread?

Categories