Why use BeginInvoke here?

I am looking at another user's code and do not have much experience with regard to multithreading. I came across this line of code:

BeginInvoke((MethodInvoker)delegate() { btnCalibrate.PerformClick(); });

I was wondering why to do it when it would work: btnCalibrate.PerformClick();

Thank you for your responses.

+4
source share
2 answers

Because if this code works in a different thread with the one that created the button in the GUI, an exception will be thrown. Background threads cannot directly invoke methods in the GUI because the GUI is not thread safe.

Of course, this is just a reasonable reason to use BeginInvoke ! But it’s not unusual to find a code that contains spells or magic spells that have just been entered for no good reason, because the author saw another example that did it this way, and therefore suggested that it should be necessary all cases. If the code you are working with is single-threaded, then it is not needed.

In particular, Windows Forms itself is single-threaded. All operations on all windows and controls occur in one thread, and all their events fire in the same thread. The use of a single GUI thread is shared through a message loop that runs continuously in the thread and reads messages from the queue. BeginInvoke's goal is to ultimately send a message to this queue, effectively saying, "When you have a moment, run this piece of code."

+5
source

To zoom in on @Earwicker a bit - Control.BeginInvoke is a way to transfer a call from one thread to the thread that owns the Control instance. In the background, it uses Win32 messages through a Win32 function called PostMessage to march the call to the PerformClick method in the ownership stream. This is necessary because of Win32 Windows and the WinForms Controls extension, being safe to access only from the thread that created it, which is usually the only thread that runs the GUI.

The reason BeginInvoke used vs. Invoke is that the former uses PostMessage and returns immediately, while the latter uses SendMessage under covers and should wait for PostMessage and wait for a response from the GUI thread. This can delay the thread BeginInvoke call, or even block the application, so BeginInvoke is the best choice here.

+1
source

Source: https://habr.com/ru/post/1301665/


All Articles