I am using following code to create and execute thread i need to stop it but cant see thread .Sleep
any ideas how can i stop for a while the execution there?
var t = new Thread(() =>
{
try
{
//Line 1
Pause here
//Line 2
Pause here
//Line 3
}
catch (Exception ca)
{
MessageBox.Show(ca.Message);
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
If you mean that you want to instruct the Thread to wait at a particular checkpoint until some other Thread tells it to continue, one good option is to use AutoResetEvent.
t.SetApartmentState(ApartmentState.STA);
I'll work from the assumption that this was intentional. Couple of things you have to do to meet the STA contract. You have to pump a message loop, call Application.Run(). And you cannot pause, that blocks any marshaled call and makes deadlock very likely.
Not a problem, when you pump a message loop you're always in an idle 'pause' state. Make code run just as you'd normally do in a GUI main thread. Application.ExitThread ends the thread.
Use the static method Thread.Sleep(int) inside your delegate
http://msdn.microsoft.com/en-us/library/d00bd51t.aspx
Suspends the current thread for a specified time.
Are you looking for the System.Threading.Thread.Sleep() method?
add this line at the top of your code:
using System.Threading;
then you can see Thread.Sleep()
Related
I have 2 threads in my program. 1 is handling a GUI and the other is doing some word automation. Lets call them GUIThread and WorkerThread.
The WorkerThread is looping through methods using recursion.
The WorkerThread is only alive while doing the word automation and the user must be able to stop the word automation. Therefore I have implemented a "Stop" button on the GUI which simply kills/terminates the WorkerThread. However if I kill the WorkerThread while it's in the middle of a method it sometimes causes a problem in my word document (this is a longer story) and that's why I want to check if the WorkerThread has finished/returned from a method before I kill it.
This is what my code does when I hit the "Stop" button:
//Stops the worker thread = stops word automation in process
workerThread.Abort();
//This blocks the thread until the workerThread has aborted
while (workerThread.IsAlive) ;
My own suggestion/workaround for the problem was to have a global variable I could set each time the WorkerThread entered and left a method but this doesn't seem right to me. I mean I think there must be an easier way to deal with it.
However if I kill the WorkerThread while it's in the middle of a method it sometimes causes a problem in my word document
This is why you should never kill a thread. You can't say what the thread was doing, whether it is safe to kill? etc etc.
Abort isn't doing what you expect it to do. Look at the documentation, it is subtle Calling this method usually terminates the thread. Note the word usually and not always.
Yes, Abort will not kill the thread always. For example if the thread was running unmanaged code, CLR will not abort the thread, instead it will wait for the thread to return to managed code.
Sameway Abort will not do its job when thread is in Constrained Execution Region, finally blocks etc.
The CLR delays thread aborts for code that is executing in a CER.
For example: Try to run the following code and see what happens.
private void IWillNeverReturn()
{
Thread thread = new Thread(() =>
{
try
{
}
finally
{
while (true)
{ }
}
});
thread.Start();
Thread.Sleep(1000);
thread.Abort();
}
Let the thread decide when it should complete, Tell the thread that it should stop as soon as it can. You tell it using CancellationToken.
If you google for Thread.Abort Evil, you'll find lot of useful resources, Here is one.
I have a little c# app with multiple threads runing, but my main thread has to wait for all of threads to finish then it can do the rest.
problem now is that im using .join() for each thread, this seems wait for each thread to finish then it goes to next thread, which makes app not really multi-threading and take long time to finish.
so I wonder if there is any way I can get around this problem or just a way to check if there are no more threads is active.
thanks
If you're hanging on to the Thread object, you can use Thread.IsAlive.
Alternately, you might want to consider firing an event from your thread when it is done.
Thread.Join() doesn't mean your application isn't multithreaded - it tells the current thread to wait for the other thread to finish, which is exactly what you want.
Doing the following:
List<Thread> threads = new List<Thread>();
/** create each thread, Start() it, and add it to the list **/
foreach (Thread thread in threads)
{
thread.Join()
}
will continue to run the other threads, except the current/main thread (it will wait until the other threads are done).
Just use Thread.Join()
Ye, as said by Cuong Le, using Task Parallel Library would be much efficient.
However, you can Create a list of Threads and then check if they are alive or not.
var threadsList = new List<Thread>();
threadsList.Add(myThread); // to add
bool areDone = true;
foreach (Thread t in threadsList) {
if (t.IsAlive)
{
areDone = false;
break;
}
}
if (areDone)
{
// Everything is finished :O
}
Run multiple at same time but wanted to wait for all of them to finish, here's a way of doing the same with Parallel.ForEach:
var arrStr = new string[] {"1st", "2nd", "3rd"};
Parallel.ForEach<string>(arrStr, str =>
{
DoSomething(str); // your custom method you wanted to use
Debug.Print("Finished task for: " + str);
});
Debug.Print("All tasks finished");
That was the most simplest and efficient i guess it can go if in C# 4.0 if you want all tasks to run through same method
Try using BackgroundWorker
It raises an event in the main thread (RunWorkerCompleted) after its work is done
Here is one sample from previously answered question
https://stackoverflow.com/a/5551376/148697
In MSDN, the description of the Thread.Abort() method says: "Calling this method usually terminates the thread."
Why not ALWAYS?
In which cases it doesn't terminate the thread?
Are there any other possibility to terminate threads?
Thread.Abort() injects a ThreadAbortException on the thread. The thread may cancel the request by calling Thread.ResetAbort(). Also, there are certain code parts, such as finally block that will execute before the exception is handled. If for some reason the thread is stuck in such a block the exception will never be raised on the thread.
As the caller has very little control over the state of the thread when calling Abort(), it is generally not advisable to do so. Pass a message to the thread requesting termination instead.
In which cases it doesn't terminate the thread?
This question is a duplicate.
What's wrong with using Thread.Abort()
Are there any other posibility to terminate threads?
Yes. Your problem is that you should never start up a thread that you cannot tell politely to stop, and it stops in a timely manner. If you are in a situation where you have to start up a thread that might be (1) hard to stop, (2) buggy, or worst of all (3) hostile to the user, then the right thing to do is to make a new process, start the thread in the new process, and then terminate the process when you want the thread to go down. The only thing that can guarantee safe termination of an uncooperative thread is the operating system taking down its entire process.
See my excessively long answer to this question for more details:
Using lock statement within a loop in C#
The relevant bit is the bit at the end where I discuss what the considerations are regarding how long you should wait for a thread to kill itself before you abort it.
Why not ALWAYS?
In which cases it doesn't termenate the thread?
For starters, a thread may catch a ThreadAbortException and cancel its own termination. Or it could perform a computation that takes forever while you're trying to abort it. Because of this, the runtime can't guarantee that the thread will always terminate after you ask it to.
ThreadAbortException has more:
When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Since the thread can do an unbounded computation in the finally blocks, or call Thread.ResetAbort() to cancel the abort, there is no guarantee that the thread will ever end.
You don't need to Abort() a thread manually. The CLR will do all of the dirty work for you if you simply let the method in the thread return; that will end the thread normally.
FileStream.Read() to a named pipe that is currently not receiving anything (read call blocks while waiting for incoming data) will not respond to Thread.Abort(). It remains inside the Read() call.
What if a thread is holding a lock and is aborted / killed ? Resources remain stuck
It works fine when when a thread calls
abort itself but not by other thread.
Abort, forcefully terminates the
affected thread even if it has not
completed its task and provides no
opportunity for the cleanup of
resources
reference MSDN
see: Managed Threading Best Practices
I can't seem to abort a thread that is stuck in a loop:
//immortal
Thread th1 = new Thread(() => { while (true) {}});
I can however abort the thread if sleeps during the loop:
//mortal
Thread th2 = new Thread(() => { while (true) { Thread.Sleep(1000); }});
ThreadAborts will not occur inside a finally block or between BeginCriticalRegion and EndCriticalRegion
Because you can catch the ThreadAbortException and call Thread.ResetAbort inside the handler.
OT: For a comprehensive, language-agnostic, questionably useful and darned funny take on concurrency, see Verity Stob!
As john feminella stated from MSDN
When this exception is raised, the runtime executes all the finally
blocks before ending the thread.
For example this Abort never ends:
var thread = new Thread(action) { IsBackground = true };
thread.Start();
Thread.Sleep(2000);
thread.Abort();
while (!thread.Join(1000))
{
Console.WriteLine(thread.ThreadState);
}
void action()
{
try
{
while (true) { }
}
catch { }
finally
{
while (true) { }
}
}
I've had cases where the thread has been too busy to hear the Abort() call, which usually results in a ThreadAbortingException being thrown to my code.
I am having a problem, for which I am not able to find a solution. The problem is as follows:
In the main thread (the default thread), I am starting a thread and then immediately in the main thread, I wait for the thread's exit by calling Thread.Join on the spawned thread. When I do that if the spawned thread tries to callback in the main thread's context by calling Dispatcher.Invoke, it hangs. Any ideas how I can allow the callback?
The callback has the logic to signal the thread to exit. Without executing the callback, the thread will never exit, and so the main thread is also stuck.
What's the point of starting a new thread if you just wait for it to complete ? Just do the work on the main thread...
I'm not exactly sure what you are asking but you may try BeginInvoke instead of Invoke
If you're only going to be waiting on the thread to terminate, you could simply have a polling loop, like this:
// var otherThread = ...;
volatile bool terminate = false;
while (!terminate)
{
Thread.Sleep(100);
}
otherThread.Join();
Then, leave it up to the callbacks to set the terminate flag to true once you're ready to join.
I had a similar problem which I finally solved in this way:
do{
// Force the dispatcher to run the queued operations
Dispatcher.CurrentDispatcher.Invoke(delegate { }, DispatcherPriority.ContextIdle);
}while(!otherthread.Join(1));
This produces a Join that doesn't block because of GUI-operations on the other thread.
The main trick here is the blocking Invoke with an empty delegate (no-operation), but with a priority setting that is less than all other items in the queue. That forces the dispatcher to work through the entire queue. (The default priority is DispatcherPriority.Normal = 9, so my DispatcherPriority.ContextIdle = 3 is well under.)
The Join() call uses a 1 ms time out, and re-empties the dispatcher queue as long as the join isn't successful.
I have another thread polling user input. This thread is the main thread and can sleep minutes at a time. If the user hits wants to quit it may be 2+ minutes before the console window shuts down which may feel not responsive.
How can i make this thread wake up from Thread.Sleep? Do i need to use another function to sleep and pass in a bool ref for it to check when the thread wake up and end?
Use Monitor.Wait instead, and call Monitor.Pulse or Monitor.PulseAll
to wake the thread up.
The solution is "Don't sleep on your UI thread". You should have a thread waiting for user input (not polling), and if you have a thread which needs to sleep (which probably isn't the case - it sounds like a hackish workaround to a different problem), then that should be separate thread that isn't handling the interface.
Have a look at the blocking queue:
http://msdn.microsoft.com/en-us/magazine/cc163427.aspx#S4
Couple of suggestions:
If your using explicit threads you can try setting ThreadType to "Background" to prevent it from blocking an exit.
Try this as how you block:
main thread:
AutoResetEvent waitingEvent = new AutoResetEvent(false);
bool doneFlag = false
Thread myUIInputThread = new Thread(someFunction);
myUIInputThread.Start(waitingEvent);
while (!doneFlag) {
doneFlag = waitingEvent.WaitOne(1000);
if (!doneFlag) {
Console.Writeline("Still waiting for the input thread...");
}
}
In some function:
public void someFunction(object state) {
Console.Write ("Enter something: ");
Console.Readline();
//... do your work ....
((AutoResetEvent)state).Set();
}
Not tested for exactness... YMMV :)