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.
Related
Below is my code in which i want to restart a thread if a condition is true .Some how i need to do it is there any way to terminate a thread and restart that thread is itpossible? for e.g
private Thread demoThread = null;
this.demoThread = new Thread(new ThreadStart(this.StartForLoop));
this.demoThread.Start();
private void StartForLoop()
{
if(i=0)
{
//restart this thread...
}
}
You can't restart a thread once it finishes executing. You can start a new thread, or use a pool of worker threads that are started and stay running looking for tasks to run and then go back to sleep.
If the tasks you want to run out of band are relatively short-lived and you need to run them frequently using the ThreadPool is recommended.
If you are targeting newer version of the .Net framework it's best to consider using the new async features in conjunction with the Tasks API as it provides a higher level of abstraction than simply using the ThreadPool directly to queue units of work.
However, if what you want to do is have a background thread wait as in a producer-consumer pattern then you could perhaps use a ManualResetEvent or Semaphore and have your thread wait on the object to become signaled. When the event is signaled, the thread can resume and consume whatever it is it needs to consume and then go to sleep again until there is more to do.
Thread objects can only run once.
If you want to start it again, you'll need to create a new Thread.
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/
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.
I am using .NET 3.5 and am trying to wrap my head around a problem (not being a supreme threading expert bear with me).
I have a windows service which has a very intensive process that is always running, I have put this process onto a separate thread so that the main thread of my service can handle operational tasks - i.e., service audit cycles, handling configuration changes, etc, etc.
I'm starting the thread via the typical ThreadStart to a method which kicks the process off - call it workerthread.
On this workerthread I am sending data to another server, as is expected the server reboots every now and again and connection is lost and I need to re-establish the connection (I am notified by the lost of connection via an event). From here I do my reconnect logic and I am back in and running, however what I easily started to notice to happen was that I was creating this worker thread over and over again each time (not what I want).
Now I could kill the workerthread when I lose the connection and start a new one but this seems like a waste of resources.
What I really want to do, is marshal the call (i.e., my thread start method) back to the thread that is still in memory although not doing anything.
Please post any examples or docs you have that would be of use.
Thanks.
You should avoid killing the worker thread. When you forcibly kill a Win32 thread, not all of its resources are fully recovered. I believe the reserved virtual address space (or is it the root page?) for the thread stack is not recovered when a Win32 thread is killed. It may not be much, but in a long-running server service process, it will add up over time and eventually bring down your service.
If the thread is allowed to exit its threadproc to terminate normally, all the resources are recovered.
If the background thread will be running continuously (not sleeping), you could just use a global boolean flag to communicate state between the main thread and the background thread. As long as the background thread checks this global flag periodically. If the flag is set, the thread can shut itself down cleanly and exit. No need for locking semantics if the main thread is the only writer and the background thread only reads the flag value.
When the background thread loses the connection to the server that it's sending data to, why doesn't it perform the reconnect on its own? It's not clear to me why the main thread needs to tear down the background thread to start another.
You can use the Singleton pattern. In your case, make the connection a static object. Both threads can access the object, which means construct it and use it.
The main thread could construct it whenever required, and the worker thread access it whenever it is available.
Call the method using ThreadPool.QueueUserWorkItem instead. This method grabs a thread from the thread pool and kicks off a method. It appears to be ideal for the task of starting a method on another thread.
Also, when you say "typical ThreadStart" do you mean you're creating and starting a new Thread with a ThreadStart parameter, or you're creating a ThreadStart and calling Invoke on it?
Have you considered a BackgroundWorker?
From what I understand, you just have a single thread that's doing work, unless the need arises where you have to cancel it's processing.
I would kill (but end gracefully if possible) the worker thread anyway. Everything gets garbage-collected, and you can start from scratch.
How often does this server reboot happen? If it happens often enough for resources to be a problem, it's probably happening too often.
The BackgroundWorker is a bit slower than using plain threads, but it has the option of supporting the CancelAsync method.
Basically, BackgroundWorker is a wrapper around a worker thread with some extra options and events.
The CancelAsync method only works when WorkerSupportsCancellation is set.
When CancelAsync is called, CancellationPending is set.
The worker thread should periodically check CancellationPending to see if needs to quit prematurely.
--jeroen
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.