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) .
Related
What happens when more than one thread tries to call a form method using Invoke which updates form controls at the same time in Winforms?
static thCount = 0;
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t1 = new System.Threading.Thread(start);
System.Threading.Thread t2 = new System.Threading.Thread(start);
t1.Start();
t2.Start();
}
private void start()
{
System.Threading.Thread.Sleep(300);
Invoke(new MethodInvoker(guiUpdate));
}
private void guiUpdate()
{
this.label1.Text = "Updated.." + (thCount++);
this.label1.Update();
}
private void Form1_Load(object sender, EventArgs e)
{
this.label1.Text = System.Threading.Thread.CurrentThread.Name;
}
Try it out! :) You'll find that neither of them can update the UI from a background thread, instead they need to use Control.BeginInvoke to invoke work on the UI thread, in which case they will execute in the order that they call BeginInvoke.
Either of the thread will not be able to update the GUI.
You might get cross thread exception if you do not check 'InvokeRequired'.
if you still want these threads to access the same method, you can use Mutual Exclusion concept.
You can find more on Mutual Exclusion here.
This question on stack overflow also explain Mutual Exclusion in detail.
Invoke blocks until the thread has finished executing the update method.
However, this is actually only a message to the GUI thread to do this and it waits until it is done. Since the GUI thread can only execute one method at a time there is no real simultaneous execution. Nothing bad happens, but the behaviour may depend on the sequence of execution.
The sequence of execution, however, depends on which thread ever finished some guaranteed atomic (lock) operation.
I've got a GUI interface which has a start and a cancel button. After starting, the main thread which is the GUI thread, is creating a second thread which will do the actual work. When pressing the cancel button, all it does is set a boolean value which tells the working thread to stop its work and end. The problem is that the main GUI thread remain stuck even though I'm sure that the working thread has finished what it was doing. Why is that?
Here is some of the code:
private Thread workerThread;
private SomeClass fs;
private void buttonSearch_Click(object sender, EventArgs e)
{
//do some initializations
fs = new SomeClass();
workerThread = new Thread(fs.WorkMethod);
workerThread.Start();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
fs.StopWork();
workerThread.Join();
}
inside SomeClass:
private bool keepWorking;
public void StopWork()
{
keepWorking= false;
}
public void WorkMethod()
{
if (keepWorking)
{
//do some stuff with recursion
}
}
does someone know why won't the main thread wake up after calling join?
I have also tried debugging to see what happens if I change the keepWorking variable to false manually and the method does reach its' end.
Your WorkMethod has a call to Invoke in there that is invoking a delegate to run on the UI thread and then block until it finishes. Since your UI thread is currently blocking on the call to Join waiting for the background thread, the UI thread is unable to call that delegate.
You now have both threads each waiting on the other, and no progress is being made. This is called a "deadlock".
Also, keepWorking should be marked as volatile as it's being accessed from multiple threads; as it stands the background thread can be accessing an outdated/cached value of that variable for quite some time after the main thread changes it. Marking it as volatile prevents the runtime from making such optimizations.
The solution here is to not block the UI thread with a call to Join. If you need to have some code execute when the background thread ends then you'll need to asynchronously fire that code when the thread finishes instead of synchronously blocking.
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.
I have a UserControl with a TreeView control called mTreeView on it. I can get data updates from multiple different threads, and these cause the TreeView to be updated. To do this, I've devised the following pattern:
all data update event handlers must acquire a lock and then check for InvokeRequired; if so, do the work by calling Invoke. Here's the relevant code:
public partial class TreeViewControl : UserControl
{
object mLock = new object();
void LockAndInvoke(Control c, Action a)
{
lock (mLock)
{
if (c.InvokeRequired)
{
c.Invoke(a);
}
else
{
a();
}
}
}
public void DataChanged(object sender, NewDataEventArgs e)
{
LockAndInvoke(mTreeView, () =>
{
// get the data
mTreeView.BeginUpdate();
// perform update
mTreeView.EndUpdate();
});
}
}
My problem is, sometimes, upon startup, I will get an InvalidOperationException on mTreeView.BeginUpdate(), saying mTreeView is being updated from a thread different than the one it was created. I go back in the call stack to my LockAndInvoke, and lo and behold, c.InvokeRequired is true but the else branch was taken! It's as if InvokeRequired had been set to true on a different thread after the else branch was taken.
Is there anything wrong with my approach, and what can I do to prevent this?
EDIT: my colleague tells me that the problem is that InvokeRequired is false until the control is created, so this is why it happens on startup. He's not sure what to do about it though. Any ideas?
It is a standard threading race. You are starting the thread too soon, before the TreeView is created. So your code sees InvokeRequired as false and fails when a split second later the native control gets created. Fix this by only starting the thread when the form's Load event fires, the first event that guarantees that all the control handles are valid.
Some mis-conceptions in the code btw. Using lock is unnecessary, both InvokeRequired and Begin/Invoke are thread-safe. And InvokeRequired is an anti-pattern. You almost always know that the method is going to be called by a worker thread. So use InvokeRequired only to throw an exception when it is false. Which would have allowed diagnosing this problem early.
When you marshal back to the UI thread, it's one thread--it can do only one thing at at time. You don't need any locks when you call Invoke.
The problem with Invoke is that it blocks the calling thread. That calling thread usually doesn't care about what get's completed on the UI thread. In that case I recommend using BeginInvoke to marshal the action back to the UI thread asynchronously. There are circumstances where the background thread can be blocked on Invoke while the UI thread can be waiting for the background thread to complete something and you end up with a deadlock: For example:
private bool b;
public void EventHandler(object sender, EventArgs e)
{
while(b) Thread.Sleep(1); // give up time to any other waiting threads
if(InvokeRequired)
{
b = true;
Invoke((MethodInvoker)(()=>EventHandler(sender, e)), null);
b = false;
}
}
... the above will deadlock on the while loop while because Invoke won't return until the call to EventHandler returns and EventHandler won't return until b is false...
Note my use of a bool to stop certain sections of code from running. This is very similar to lock. So, yes, you can end up having a deadlock by using lock.
Simply do this:
public void DataChanged(object sender, NewDataEventArgs e)
{
if(InvokeRequired)
{
BeginInvoke((MethodInvoker)(()=>DataChanged(sender, e)), null);
return;
}
// get the data
mTreeView.BeginUpdate();
// perform update
mTreeView.EndUpdate();
}
This simply re-invokes the DataChanged method asynchronously on the UI thread.
The pattern as you have shown it above looks 100% fine to me (albeit with some extra unnecessary locking, however I can't see how this would cause the problem you have described).
As David W points out, the only difference between what you are doing and this extension method is that you directly access mTreeView on the UI thread instead of passing it in as an argument to your action, however this will only make a difference if the value of mTreeView changes, and in any case you would have to try fairly hard to get this to cause the problem you have described.
Which means that the problem must be something else.
The only thing that I can think of is that you may have created mTreeView on a thread other than the UI thread - if this is the case then accessing the tree view will be 100% safe, however if you try and add that tree view to a form which was created on a different thread then it will go bang with an exception similar to the one that you describe.
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.