how to close a thread containing a blocking method in C# - c#

I create a thread to handle a blocking method in my code. this way, my code can do other things beside running that blocking method.
question: how can I terminate the thread properly? do I have to unblock the blocking method, then terminate the thread. or can I just terminate the thread without worrying about any ugly crashing?

Call yourthread.Abort(). It's not like in the old days where this would cause you to break everything when resources and locks weren't released, now this causes quite a nice exception to be raised that can be handled in the normal way...
http://msdn.microsoft.com/en-us/library/system.threading.thread.abort.aspx
When I say "the normal way" it seems that thread abort exception auto re-raises (quite a nice trick)
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx
but that wouldn't stop you being a douche and kicking off another big thing in the catch block...

You have some options. If you don't care if the operation completes when the application is going down you might be better off using a ThreadPool thread via QueueUserWorkItem or (as Servy suggests in comments) set the IsBackground property of your thread to true, which will allow the process to exit without the thread exiting.
If you do care about the operation completing and/or have cleanup logic that needs to be run on shutdown you probably don't really want to use Thread.Abort, at least not as your goto strategy. What I use is something similar to this:
public abstract class DisposableThread : IDisposable
{
private ManualResetEvent exiting = new ManualResetEvent(false);
private Thread theThread;
private TimeSpan abortTimeout;
public DisposableThread():
this(TimeSpan.FromMilliseconds(100))
{
}
public DisposableThread(TimeSpan abortTimeout)
{
this.abortTimeout = abortTimeout;
theThread = new Thread((_) => ThreadProc());
}
protected virtual void ThreadProc()
{
while(!exiting.WaitOne(0))
{
WorkUnit(exiting);
}
ThreadCleanup();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
exiting.Set();
if (!theThread.Join(abortTimeout))
{
// logme -- the thread didn't shutdown gracefully
theThread.Abort();
while (!theThread.Join(1000))
{
// logme -- the thread is doing something dumb in an exception handler
}
}
exiting.Dispose();
}
// WorkUnit should return as quickly as safe if the exiting handle is set
// If it doesn't the thread will be aborted if it takes longer than abortTimeout
protected abstract void WorkUnit(WaitHandle exiting);
// override if you need to cleanup on exit
protected virtual void ThreadCleanup() { }
}
Which gives your thread a chance to exit gracefully and only aborts if a graceful exit fails.

OK,
found my answer. I gotta declare the threads so that references can be made to them. then, I end the nested thread (which has HandleClientComm()) first, then close the TCP_Client (if not null) and the TCP_Listener. then I end the ListenThread(). also, the TCP_Listener.Pending() method mentioned here Proper way to stop TcpListener must be implemented.

Related

Should I implement IDisposable for a class containing a Thread

I have a class that uses the Thread class:
class A
{
public Thread thread
{ get; set; }
}
Should I implement IDisposable and set Thread property to null?
class A : IDisposable
{
public Thread Thread
{ get; set; }
protected bool Disposed
{ get; set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.Disposed)
{
if (disposing)
{
if (Thread != null)
Thread = null;
}
Disposed = true;
}
}
}
Or not?
Why?
You implement IDisposable only when your class is handling an unmanaged object, resources or other IDisposable objects. A Thread is not an unmanaged object and will get garbage collected when nothing is referencing it or when the process handling it is terminated. Since Thread is not implementing IDisposable, your class referencing it does not need to implement it either.
Optionally, for IDisposable within the scope of a method, they can be wrapped in a using statement and the Dispose() method is automatically called when the scope is exited.
It depends what your thread is doing. If your thread is performing a long running task that may run indefinitely, then I would consider that thread as a resource (which will not be garbage collected). For example consider if the thread is designed to poll some state indefinitely, or consume items from a queue (like a thread-pool thread consumes tasks or a TCP server consumes new connections) etc. In this case, I would say the natural effect of disposing your class would be to free up this thread resource. Setting it to null is not really useful in this case. Rather Dispose should probably involve flagging a synchronization event (or maybe a CancellationToken) to notify the thread that it should finish up its infinite task, and then the disposing thread should wait some time for the thread to finish (join). As always with joins, be careful of a deadlock scenario and consider some alternative action if the thread refuses to terminate. For obvious reasons I would not do this join in the finalizer.
As an example of what I'm meaning, consider the scenario where your class A is actually class MyTcpListener, designed to listen and wait for new TCP connections on a given port indefinitely. Then consider what you expect following (somewhat unlikely) code to do:
using (MyTcpListener listener = new MyTcpListener(port:1234))
{
// Do something here
}
// Create another one. This would fail if the previous Dispose
// did not unbind from the port.
using (MyTcpListener listener = new MyTcpListener(port:1234))
{
// Do something else here
}
Assuming I know the constructor of MyTcpListener creates a listener thread, I would expect that after the Dispose call has returned that the MyTcpListener would no longer be bound to the TCP port - i.e. that the TCP listener thread would have fully terminated. It goes without saying that if you didn't provide some mechanism to stop the listener that there would be a resource leak. The stopping mechanism could be a call to some method "Stop", but I personally think the "Dispose" pattern fits this scenario more cleanly since forgetting to stop something does not generally imply a resource leak.
Your code may call for different assumptions, so I would suggest judging it on the scenario. If your thread is short-running, e.g. it has some known finite task to complete and then it will terminate on its own, then I would say that disposing is less critical or perhaps useless.

Dispose Unmanaged Resources in Thread

I have a class that uses unmanaged resources in a thread, it can also go to sleep when not in use. I am implementing dispose for it, please see example code below (noting it is a dumbed down version of my app). I added while(TheThread.IsAlive()); as disposed could be set to true before DestroySomeUnmangedResouces() has executed. I don't think what I have done is correct so would be grateful if someone could suggest a better model.
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
//managed
}
//unmanged
_stopTheThread = true;
startTheThreadEvent.Set();
while(TheThread.IsAlive());
}
disposed = true;
}
private void TheThread()
{
while (!_stopTheThread)
{
if (state == State.Stopped)
{
// wait till a start occurs
startTheThreadEvent.WaitOne();
}
switch (state)
{
case Init:
CreateSomeUnmangedResouces();
break;
case Run:
DoStuffWithUnmangedResouces();
break;
case Stop:
DestroySomeUnmangedResouces();
break;
} // switch
}
// Release unmanaged resources when component is disposed
DestroySomeUnmangedResouces();
}
You seem to want to wait until your worker thread has exited. For this you can simply use Thread.Join() which will block until your thread has exited.
Currently you are eating 100% CPU on your wait thread because you do poll if the worker thread is still alive. A less resource intensive variant is a throttled polling where you sleep between your checks at least a timeslice (15ms).
But the by far best approach is to wait for a synchronisation primitive which gets signaled and wakes up your thread when a condtion becomes true. Thead.Join is therefore the way to go.
private readonly ManualResetEvent _stopEvent = new ManualResetEvent(false);
private readonly ManualResetEvent _threadStoppedEvent = new ManualResetEvent(false);
private bool disposed;
private int checkInterval = 10;//ms
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
//managed
}
//unmanged
_stopEvent.Set();
_threadStoppedEvent.WaitOne();
}
disposed = true;
}
private void TheThread()
{
CreateSomeUnmangedResouces();
while (!_stopEvent.WaitOne(checkInterval))
{
DoStuffWithUnmangedResouces();
}
DestroySomeUnmangedResouces();
_threadStoppedEvent.Set();
}
Or you can use Thread.Join() instead of _threadStoppedEvent if your thread isn't background
The caller calling dispose should mop up the thread - the best way is to call Join on it as Alois has suggested. Once the thread has joined, then you can destroy the unmanaged resources which will now happen on the callers thread. E.g.:
protected virtual void
Dispose
(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if(TheThread != null)
{
// send a signal to stop the thread.
_stopTheThread = true;
startTheThreadEvent.Set();
// Join the thread - we could timeout here but it should be the
// responsibility of the thread owner to ensure it exits
// If this is hanging then the owning object hasn't terminated
// its thread
TheThread.Join();
TheThread = null;
}
}
// Now deal with unmanaged resources!
DestroySomeUnmangedResouces();
}
disposed = true;
}
One drawback of this approach is that we are assuming the thread will eventually exit. It could hang, meaning the signals to stop the thread was not enough. There are overloads for Join which include timeouts, which could be used to prevent hanging the calling thread (see comment in code sample above).
If a running thread holds a direct or indirect strong reference to an object, such reference will prevent the object from becoming eligible for garbage collection. There's thus not really any reason to have a finalizer on such an object.
If, however, the thread will only be relevant as long as a reference some other particular object is held by something other than the thread, it may be useful for the thread to hold a WeakReference to that other object, and shut itself down if that other object goes out of scope. This shutdown could be accomplished either by having the thread periodically check the IsAlive property of the WeakReference, or by having the other object include a finalizer which would signal the thread to shut down. Although periodic polling for such things is in some sense icky, and using a finalizer could somewhat hasten the shutdown of the thread, I think polling is probably still better. While it's possible for a finalizer to notify a thread that it should do something, and there are times when doing so may be appropriate, in general the fact that an object was finalized meant that nobody was overly concerned about prompt cleanup. Adding another few seconds' delay before the thread shuts down probably won't hurt anything.

'Deadlock' with only one locked object?

I am having a problem with multi threading in C#.
I use an event to update a label in a form from another thread, for which I need to use the Invoke() command of course.
That part is also working fine.
However, the user can close the form and here the program can crash if the event is sent at an unfortunate time.
So, I thought I would simply override the Dispose() method of the form, set a boolean to true within locked code, and also check that boolean and invoke the event in locked code.
However, every time I close the form the program freezes completely.
Here are the mentioned parts of the code:
private object dispose_lock = new object();
private bool _disposed = false;
private void update(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler handler = new EventHandler(update);
lock (dispose_lock)
{
if (_disposed) return;
Invoke(handler); // this is where it crashes without using the lock
}
return;
}
label.Text = "blah";
}
protected override void Dispose(bool disposing)
{
eventfullObject.OnUpdate -= update;
lock (dispose_lock) // this is where it seems to freeze
{
_disposed = true; // this is never called
}
base.Dispose(disposing);
}
I hope anyone here has any idea what is wrong with this code.
Thank you in advance!
What you're not taking into account is that delegate passed to Invoke is called asynchronously on the UI thread. Calling Invoke posts a message to the forms message queue and is picked up some time later.
What happens is not:
UI Thread Background Thread
Call update()
take lock
Call Invoke()
Call update()
release lock
Call Dispose()
take lock
release lock
But instead:
UI Thread Background Thread
Call update()
take lock
Call Invoke()
block until UI Thread processes the message
Process messages
...
Dispose()
wait for lock ****** Deadlock! *****
...
Call update()
release lock
Because of this, the background thread can hold be holding the lock while the UI thread is trying to run Dispose
The solution is much simpler than what you tried. Because of the Invoke is posted asynchronously there is no need for a lock.
private bool _disposed = false;
private void update(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler handler = new EventHandler(update);
Invoke(handler);
return;
}
if (_disposed) return;
label.Text = "blah";
}
protected override void Dispose(bool disposing)
{
eventfullObject.OnUpdate -= update;
_disposed = true; // this is never called
base.Dispose(disposing);
}
The _disposed flag is only read or written on the UI thread so there is no need for locking. Now you call stack looks like:
UI Thread Background Thread
Call update()
take lock
Call Invoke()
block until UI Thread processes the message
Process messages
...
Dispose()
_disposed = true;
...
Call update()
_disposed is true so do nothing
One of the dangers of using Control.Invoke is that it could be disposed on the UI thread at an unfortunate time as you suggested. The most common way this occurs is when you have the following order of events
Background Thread: Queues a call back with Invoke
Foreground Thread: Dispose the Control on which the background called Invoke
Foreground Thread: Dequeues the call back on a disposed Control
In this scenario the Invoke will fail and cause an exception to be raised on the background thread. This is likely what was causing your application to crash in the first place.
With the new code though this causes a dead lock. The code will take the lock in step #1. Then the dispose happens in the UI at step #2 and it's waiting for the lock which won't be freed until after step #3 completes.
The easiest way to deal with this problem is to accept that Invoke is an operation that can and will fail hence needs a try / catch
private void update(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler handler = new EventHandler(update);
try
{
Invoke(handler);
}
catch (Exception)
{
// Control disposed while invoking. Nothing to do
}
return;
}
label.Text = "blah";
}
I really would go simple here. Instead of implementing tricky thread-safe code, I would simply catch the exception and do nothing if it fails.
Assuming it's a ObjectDisposedException:
try
{
this.Invoke(Invoke(handler));
}
catch (ObjectDisposedException)
{
// Won't do anything here as
// the object is not in the good state (diposed when closed)
// so we can't invoke.
}
It's simpler and pretty straightforward. If a comment specifies why you catch the exception, I think it's OK.
Why don't you just use BeginInvoke rather than Invoke - this won't block the background thread. It doesn't look like there is any specific reason why the background thread needs to wait for the UI update to occur from what you have shown
Another deadlocking scenario arises when calling Dispatcher.Invoke (in
a WPF application) or Control.Invoke (in a Windows Forms application)
while in possession of a lock. If the UI happens to be running another
method that’s waiting on the same lock, a deadlock will happen right
there. This can often be fixed simply by calling BeginInvoke instead
of Invoke. Alternatively, you can release your lock before calling
Invoke, although this won't work if your caller took out the lock. We
explain Invoke and BeginInvoke in Rich Client Applications and Thread
Affinity.
source: http://www.albahari.com/threading/part2.aspx
Just incase none of the other answers are the culprit, is there other code that terminates the thread that isn't posted? I'm thinking you might be using plain Threads and not a BackgroundWorker, and might have forgotten to set Thread.isBackround to true
IMO Dispose is too late...
I would recommend putting some code into FormClosing which is called before Dispose happens AFAIK.
For such a case I usually tend to use a different (atomic) pattern for your check - for example via the Interlocked class.
private long _runnable = 1;
private void update(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler handler = new EventHandler(update);
if (Interlocked.Read (ref _runnable) == 1) Invoke(handler);
return;
}
label.Text = "blah";
}
In FormClosing you just call Interlocked.Increment (ref _runnable) .

Should a class with a Thread member implement IDisposable?

Let's say I have this class Logger that is logging strings in a low-priority worker thread, which isn't a background thread. Strings are queued in Logger.WriteLine and munched in Logger.Worker. No queued strings are allowed to be lost. Roughly like this (implementation, locking, synchronizing, etc. omitted for clarity):
public class Logger
{
private Thread workerThread;
private Queue<String> logTexts;
private AutoResetEvent logEvent;
private AutoResetEvent stopEvent;
// Locks the queue, adds the text to it and sets the log event.
public void WriteLine(String text);
// Sets the stop event without waiting for the thread to stop.
public void AsyncStop();
// Waits for any of the log event or stop event to be signalled.
// If log event is set, it locks the queue, grabs the texts and logs them.
// If stop event is set, it exits the function and the thread.
private void Worker();
}
Since the worker thread is a foreground thread, I have to be able to deterministically stop it if the process should be able to finish.
Question: Is the general recommendation in this scenario to let Logger implement IDisposable and stop the worker thread in Dispose()? Something like this:
public class Logger : IDisposable
{
...
public void Dispose()
{
AsyncStop();
this.workerThread.Join();
}
}
Or are there better ways of handling it?
That would certainly work - a Thread qualifies as a resource, etc. The main benefit of IDisposable comes from the using statement, so it really depends on whether the typical use for the owner of the object is to use the object for a duration of time in a single method - i.e.
void Foo() {
...
using(var obj = YourObject()) {
... some loop?
}
...
}
If that makes sense (perhaps a work pump), then fine; IDisposable would be helpful for the case when an exception is thrown. If that isn't the typical use then other than highlighting that it needs some kind of cleanup, it isn't quite so helpful.
That's usually the best, as long as you have a deterministic way to dispose the logger (using block on the main part of the app, try/finally, shutdown handler, etc).
It may be a good idea to have the thread hold a WeakReference to the managing object, and periodically check to ensure that it still exists. In theory, you could use a finalizer to nudge your thread (note that the finalizer, unlike the Dispose, should not do a Thread.Join), but it may be a good idea to allow for the possibility of the finalizer failing.
You should be aware that if user doesn't call Dispose manually (via using or otherwise) application will never exit, as Thread object will hold strong reference to your Logger. Answer provided by supercat is much better general solution to this problem.

How to kill a thread instantly in C#?

I am using the thread.Abort method to kill the thread, but it not working. Is there any other way of terminating the thread?
private void button1_Click(object sender, EventArgs e)
{
if (Receiver.IsAlive == true)
{
MessageBox.Show("Alive");
Receiver.Abort();
}
else
{
MessageBox.Show("Dead");
Receiver.Start();
}
}
I am using this but every time I get the Alive status, Receiver is my global thread.
The reason it's hard to just kill a thread is because the language designers want to avoid the following problem: your thread takes a lock, and then you kill it before it can release it. Now anyone who needs that lock will get stuck.
What you have to do is use some global variable to tell the thread to stop. You have to manually, in your thread code, check that global variable and return if you see it indicates you should stop.
You can kill instantly doing it in that way:
private Thread _myThread = new Thread(SomeThreadMethod);
private void SomeThreadMethod()
{
// do whatever you want
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
_myThread.Abort();
}
I always use it and works for me:)
You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.
Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.
In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.
The code that tries to stop the thread should do the following:
running_ = false;
threadInstance_.Interrupt();
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
threadInstance_.Abort();
}
thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.
C# Thread.Abort is NOT guaranteed to abort the thread instantaneously. It will probably work when a thread calls Abort on itself but not when a thread calls on another.
Please refer to the documentation: http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx
I have faced this problem writing tools that interact with hardware - you want immediate stop but it is not guaranteed. I typically use some flags or other such logic to prevent execution of parts of code running on a thread (and which I do not want to be executed on abort - tricky).

Categories

Resources