I’ve got a code block that has to be executed in the same thread as the window. So I’d like call Form.Invoke for this block. But the method, containing the code block, can be called from different threads and one of them is the window thread.
So my question is: Is it ok to just use Form.Invoke although the method might be called already in the right thread? Or does this generate an overhead or even be a possible source of error?
Yes it is fine to call
Invokefrom the thread that owns the handle.The overwhelming majority of code samples suggest that you should test
InvokeRequiredbefore deciding whether or not to callInvoke.However, this leads to rather cluttered code and if you must support calls from non-GUI threads then I recommend that you simply call
Invokedirectly in all cases. There is a small overhead versus callingInvokeRequiredand then the delgate directly – see Hans Passant’s comments to the question. However, so long as the delegate is performing significant work, or this code is not in a hot spot, the overhead should matter less than the code clarity.What’s more
InvokeRequiredcan give misleading results in the control’s handle has not yet been allocated. The documentation states:So I would take the advice from the final quoted paragraph above and replace the risky
InvokeRequiredcode above with: