Restarting And Termination a thread - c#

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.

Related

How can I make a thread wait until another thread is wating (C#)

I have a consumer thread that creates some worker threads. These threads must switch between active and waiting states. When all worker threads are in the waiting states, it means that the current job is done. How can I make the consumer thread wait for all the worker threads to be in the waiting state? I want a behavior very similar to Thread.Join() on all worker threads, however, I want the threads to keep running for the next job. I cannot create new threads because the jobs are in a tight loop and creating new threads is costly.
As far as I am aware there is no mechanism to do what you wish. (Thread.Join but since you can't block that is not an option)
From the info you provided it sounds like your really building a state machine, just across multiple threads.
I would create a Singleton and have that act as a state machine. Threads could signal to the Singleton there status.
It sounds like you have an indeterminate number of threads, so you would need to put the status of each in a collection. I would look here Thread Safe Collections to find the right fit for how you wish to store your state information.
Hope this helps.
Apologies for the brief answer (may expand later), but you probably the WaitHandle.WaitAll method, combined with a ManualResetEvent. You would pass your ManualResetEvent objects into each worker thread when they're created, signal them when they become idle, and pass the entire set of handles into the WaitHandle.WaitAll method to wake the observing thread when they're complete. You can also use the timeout feature of this method if you want to periodically run some kind of task while waiting, or perform some kind of operation if the task is taking too long.
Note that if your worker threads are intended to terminate when the operation is complete (wasn't totally clear if this is the case), it might be more appropriate to spawn them as tasks and use Task.WaitAll instead.
Edit: On a quick re-read, it sounds like you do want to be using tasks rather than trying to re-use full worker threads. Tasks use threads which have been allocated from the thread pool, eliminating that thread creation overhead you were worried about, because the threads will (generally) be ready and waiting for work. You can simply spawn each task and wait for them all to be finished.

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.

Background threading in c#

I am currently working with threading and backgroundworker in c#. The problem im having is that this. Say i have a main thread for user interaction and a worker thread to process txt files(various editing operations). Then after the backgroundthread runs its contents once, i have a timer start that performs another set of operations. I want these new operations that the timer runs ever x minutes to be run in the same background thread without running the previous txt related operations it ran before the timer started. How can this be done?
You should just use a System.Timers.Timer, which will run its callback on a thread pool thread.
It shouldn't matter which specific thread you run on (as long as it's not the UI thread).
If, for some reason, it does matter (eg, if you're using a single-threaded COM object), you'll need to make a dedicated thread that waits for things to do using a thread-safe queue of delegates.
You want to use an Event Driven method to execute function calls on your worker thread from your UI thread. The way to accomplish this is using BeginInvoke, you can read more about how to use it here: http://www.dreamincode.net/forums/topic/35616-cross-thread-communication-in-c%23/
Add a while loop to the end of your background worker:
while(!stop) { Thread.Sleep(yourIntervalinMilliseconds); ... }
I'd create a stop bool somewhere that the thread looks at when you want it to kick out.

Sending Events to a specific Thread

I have a situation in which I want a thread to process some sequential logic. This thread would need to interact with the main thread on occasion in order to update user input. But it should continue running otherwise without bothering the main thread. I am hopping to do this in an event-driven manner, so that the main thread doesn't have to pole the other thread for interrupts. What is the best way to do this? Is there an event-driven technique to communicating between threads much like there is in MFC?
I am using Visual Studio 2008 and (obviously) the .Net 3.5 framework.
Use the BackgroundWorker component.
Here you can find the best and complete tutorial about threading in C#, with code samples and examples.
AutoResetEvent and ManualResetEvent might be what you are after. Basically your main thread would wait using the various Wait methods of these classes until you signal from your other thread using the Set method. Then your wating thread will resume and continue with whatever comes afer Wait.
This is as good as it gets for an event-style. You have to wait and listen to receive an react on an event. How else are you supposed to stop your thread work in case you get an event gracefully? This is not possible with threads in general in any language.
Your only other possibility is frequent interrupting and polling.
Have a look at .Net Reactive Extensions IObservable and in particular the SubscribeOn and ObserveOn extension methods.
ObserveOn is where the work is done ( your background thread ), SubscribeOn is where the notifications go ( your UI thread ).
If you are using the BackgroundWorker you can raise a Progress event.
Here's an example on how to update a progress bar.
Ah ha! there is an event-driven way to do it. I borrowed the Dispatcher from WPF. I just give the spinning thread access to the main thread's CurrentDispatcher I let the thread spin and when it needs attention it invokes a delegate on the Dispatcher and sleeps waiting for the main thread to interrupt it. I know I could use Invoke instead of BeginInvoke, but I needed to use the interrupt because the method that restarts the worker thread is not a synchronous part of the dispatched delegates stack.
For better or worse, here is my code:
private void Run()
{
while (true)
{
...
// Need attention from the main thread
// "_main" is the main thread's Dispatcher instance.
_main.BeginInvoke(new MyEventHandler(OnNeedsAttention), this, new MyEventArgs(...));
try
{
Thread.Sleep(Timeout.Infinite);
}
catch (ThreadInterruptedException) { }
}
}

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