Anytime the beginner asks something like: How to update the GUI from another thread in C#?, the answer is pretty straight:
if (foo.InvokeRequired)
{
foo.BeginInvoke(...)
} else {
...
}
But is it really good to use it? Right after non-GUI thread executes foo.InvokeRequired
the state of foo
can change. For example, if we close form right after foo.InvokeRequired
, but before foo.BeginInvoke
, calling foo.BeginInvoke
will lead to InvalidOperationException
: Invoke or BeginInvoke cannot be called on a control until the window handle has been created. This wouldn't happen if we close the form before calling InvokeRequired
, because it would be false
even when called from non-GUI thread.
Another example: Let's say foo
is a TextBox
. If you close form, and after that non-GUI thread executes foo.InvokeRequired
(which is false, because form is closed) and foo.AppendText
it will lead to ObjectDisposedException
.
In contrast, in my opinion using WindowsFormsSynchronizationContext
is much easier - posting callback by using Post
will occur only if thread still exists, and synchronous calls using Send
throws InvalidAsynchronousStateException
if thread not exists anymore.
Isn't using WindowsFormsSynchronizationContext
just easier? Am I missing something? Why should I use InvokeRequired-BeginInvoke pattern if it's not really thread safe? What do you think is better?
BeginInvoke
andInvoke
on some magiccontrolToSendTo
. See also my comment to Daniels answer. – Without