The situation is as follows: a thread timer (from System.Threading.Timer) runs in an interval and use a object to lock and do something. An UI timer (System.Windows.Forms.Timer) do also thinks on the form by interval and using the same object. So he locks this object also.
Sometimes the thread timer will do invoke the UIThread as follow:
lock (_lockobj)
{
form.Invoke(new MethodInvoker(delegate
{ // Do somethings on form }));
}
The problem is that this call will ‘sleep’ because the same lock on ‘_lockobj’ is happen by the Form timer (which sleep also). So a deadlock is happen (this is what it is?).
I think it is clearly for me what is happening here but how to solve this. Or is this a design failure? Or maybe there are functions available that help me with this?
Question is: is it maybe possible that a not-UIThread invoking the form when the UIThread is sleeping?
Thanks.
This is clearly a deadlock. You must not call into other thread while holding a lock.
Explanation:
Imagine that the timer thread gets the lock, and is going to call to the UI thread. At the very same moment, the UI thread is trying to obtain the lock, and now waits for it to be released. So return to the first thread: the call into the UI thread cannot finish, because the UI thread is waiting. Deadlock.
My suggestion would be: get rid of all locking, and marshal all the operations into the UI thread. This way your calls are obviously serial (all of them happen in the same thread!), so there’s no need for locking.