Is lock need with this.Invoke
I came across a third-party piece of code which is using invoke to update a control, but the invoke is inside a lock statement eg
lock (mi)
{
this.Invoke(mi);
}
where mi is System.Windows.Forms.MethodInvoker mi.
The method that is called is开发者_如何学Python just updating one windows control (a listbox) and is initialised when the usercontrol is created and never changed.
So two questions
- Is there any need for the lock?
- Is it likely to cause problems?
Using a lock around Control.Invoke
is asking for trouble. You're basically saying, "I'll wait until the other thread has handled my delegate" - but if that thread (the UI thread) tries to acquire the same lock, it won't be able to because the worker thread already has it. Bang - instant deadlock.
With BeginInvoke
it wouldn't be a problem, but it still wouldn't be a good idea. Basically this looks like the code of someone whose idea of making code thread-safe is to slap locks left, right and centre.
Now as the code is locking on the delegate reference, it's hard to say whether anything else will try to acquire the same lock... but if it doesn't, the lock is pretty pointless to start with.
精彩评论