Starting new theard from another thread and abort it C# - 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/

Related

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.

How to restart a Thread in C# .Net 4.0?

I'm using C# .Net4.0 in VS 2010.
How do I restart a Thread?
Its like I want to Abort() the thread and Start() it from the beginning again?
Is it possible?
Abort a thread is often a bad idea. He is an advisor. If it's an infinite loop, a boolean used to stop the thread without the abortion.
bool run = true;
Thread thread = new Thread(method);
thread.start();
private void method()
{
while(run)
{
}
}
To stop the thread, just set the boolean to false and normally, you can restart it later.
create new instance of thread and execute again.
thread1= new Thread();
thread1.start();
Thread.Abort does not guarantee that the thread will terminate. For instance, if you have a long running query, Abort will not terminate the execution of the query, or the cancellation of the thread. In fact, the thread will live on until the query completes.
If you're doing everything in managed code and not getting locked up by unmanaged resources, and you must abort a thread, thread.Abort() is perfectly fine.
However, you cannot call Start on a thread that has been terminated. You'll have to create another Thread and call Start on that thread. Thread creation is somewhat expensive, memory wise, in .NET (in comparison with other langauges), so there are some drawbacks.
When you want to re-start the thread from the beginning, you actually want to restart an execution of certain function (code flow) on the thread. When you create a thread and pass a function for execution, a thread's life will be terminated as soon as the function finishes its own execution. You just need to change your code design that will allow to restart the function with recreating a new thread.
But for short functions I would advise to use ThreadPool.
Since you are using .NET 4.0, where MS had introduced the "Cooperative Cancellation Framework". You can read more from this blog.
Dealing directly with Thread is (more and more) discouraged.

killing a thread which is in blocking state

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.

Thread, abort and wait

I am aborting a thread (will be threads soon enough) and the problem is i need to stall until all threads have been aborted.
After doing the Thread.Abort(); I thought of using the Thread.Join() to wait until its been fully aborted. However that doesnt work. It just waits forever. How can i abort each thread and wait until its done before continuing?
Additional information: If your curious why - in this case I am closing a window, I pass a delegate func into the thread which it calls when its done (or aborted). If I dont stall then the window will close and the function will call invalid handles/objs. I can easily use the same method, stick a flag in and loop & sleep until all flags are set but that doesnt feel right.
I've learnt from many years experience with threads that there are a couple of rules that, if followed, make life a lot easier.
The one pertinent to this question is:
let threads control their own resources, including their lifetime.
I wouldn't abort a thread, I'd simply set up a communications method between the threads creator and the thread itself to signal the thread to terminate, and then let the thread itself shut down.
This method can often be as simple as a write-by-creator/read-by-thread flag which controls the threads main loop. If the thread has long running tasks while in the loop, you should also check periodically.
Then the creator thread should just join until the thread exits. Properly designed, you can set an upper limit to the time this will take.
Use a synchronisation object such as an Event. For example, each background thread has an Event associated with it. When the thread is terminating, it signals the Event. The main thread does a WaitHandle.WaitAll on the set of Events, and proceeds only when all Events are signalled.
Be warned that if there is a chance that the background threads will take a long time to terminate, blocking the main thread while waiting for them would create a bad user experience. So if this is the case, you may want to hide the window before blocking. Also, you'll want to test what the impact of this is on your callback delegate -- if the UI thread is blocked in a wait, will it be able to handle your delegate?
Might not a better design be not to call the delegate if the thread is being killed due to the window closing? Just have the main thread tell the background threads why they are terminating and have them skip the callback if the reason is "window closing." (This assumes that you are communicating with the threads, as Pax rightly recommends, rather than just calling Abort.)

How do I abort CCR threads\tasks?

I want to implement a timeout on the execution of tasks in a project that uses the CCR. Basically when I post an item to a Port or enqueue a Task to a DispatcherQueue I want to be able to abort the task or the thread that its running on if it takes longer than some configured time. How can I do this?
Can you confirm what you are asking? Are you running a long-lived task in the Dispatcher? Killing the thread would break the CCR model, so you need to be able to signal to the thread to finish its work and yield. Assuming it's a loop that is not finishing quick enough, you might choose to enqueue a timer:
var resultTimeoutPort = new Port<DateTime>();
dispatcherQueue.EnqueueTimer(TimeSpan.FromSeconds(RESULT_TIMEOUT),
resultTimeoutPort);
and ensure the blocking thread has available a reference to resultTimeoutPort. In the blocking loop, one of the exit conditions might be:
do
{
//foomungus amount of work
}while(resultTimeoutPort.Test()==null&&
someOtherCondition)
Please post more info if I'm barking up the wrong tree.
You could register the thread (Thread.CurrentThread) at the beginning of your CCR "Receive" handler (or in a method that calls your method via a delegate). Then you can do your periodic check and abort if necessary basically the same way you would have done it if you created the thread manually. The catch is that if you use your own Microsoft.Ccr.Core.Dispatcher with a fixed number of threads, I don't think there is a way to get those threads back once you abort them (based on my testing). So, if your dispatcher has 5 threads, you'll only be able to abort 5 times before posting will no longer work regardless of what tasks have been registered. However, if you construct a DispatcherQueue using the CLR thread pool, any CCR threads you abort will be replaced automatically and you won't have that problem. From what I've seen, although the CCR dispatcher is recommended, I think using the CLR thread pool is the way to go in this situation.

Categories